es6.js 4.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979
  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. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers.slice();
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers ? samplers.slice() : [];
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. var vertexSource;
  197. var fragmentSource;
  198. if (baseName.vertexElement) {
  199. vertexSource = document.getElementById(baseName.vertexElement);
  200. if (!vertexSource) {
  201. vertexSource = baseName.vertexElement;
  202. }
  203. }
  204. else {
  205. vertexSource = baseName.vertex || baseName;
  206. }
  207. if (baseName.fragmentElement) {
  208. fragmentSource = document.getElementById(baseName.fragmentElement);
  209. if (!fragmentSource) {
  210. fragmentSource = baseName.fragmentElement;
  211. }
  212. }
  213. else {
  214. fragmentSource = baseName.fragment || baseName;
  215. }
  216. this._loadVertexShader(vertexSource, function (vertexCode) {
  217. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  218. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  219. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  220. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  221. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  222. if (baseName) {
  223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  227. }
  228. else {
  229. _this._vertexSourceCode = migratedVertexCode;
  230. _this._fragmentSourceCode = migratedFragmentCode;
  231. }
  232. _this._prepareEffect();
  233. });
  234. });
  235. });
  236. });
  237. });
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShader = function (vertex, callback) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. callback(vertexCode);
  352. return;
  353. }
  354. }
  355. // Base64 encoded ?
  356. if (vertex.substr(0, 7) === "base64:") {
  357. var vertexBinary = window.atob(vertex.substr(7));
  358. callback(vertexBinary);
  359. return;
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  364. return;
  365. }
  366. var vertexShaderUrl;
  367. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  368. vertexShaderUrl = vertex;
  369. }
  370. else {
  371. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  372. }
  373. // Vertex shader
  374. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  375. };
  376. /** @ignore */
  377. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  378. if (BABYLON.Tools.IsWindowObjectExist()) {
  379. // DOM element ?
  380. if (fragment instanceof HTMLElement) {
  381. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  382. callback(fragmentCode);
  383. return;
  384. }
  385. }
  386. // Base64 encoded ?
  387. if (fragment.substr(0, 7) === "base64:") {
  388. var fragmentBinary = window.atob(fragment.substr(7));
  389. callback(fragmentBinary);
  390. return;
  391. }
  392. // Is in local store ?
  393. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  394. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  395. return;
  396. }
  397. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  398. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  399. return;
  400. }
  401. var fragmentShaderUrl;
  402. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  403. fragmentShaderUrl = fragment;
  404. }
  405. else {
  406. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  407. }
  408. // Fragment shader
  409. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  410. };
  411. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  412. // Rebuild shaders source code
  413. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  414. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  415. vertexCode = prefix + vertexCode;
  416. fragmentCode = prefix + fragmentCode;
  417. // Number lines of shaders source code
  418. var i = 2;
  419. var regex = /\n/gm;
  420. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  421. i = 2;
  422. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. // Dump shaders name and formatted source code
  424. if (this.name.vertexElement) {
  425. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  426. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  427. }
  428. else if (this.name.vertex) {
  429. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  430. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  431. }
  432. else {
  433. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  434. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  435. }
  436. };
  437. ;
  438. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  439. var preparedSourceCode = this._processPrecision(sourceCode);
  440. if (this._engine.webGLVersion == 1) {
  441. callback(preparedSourceCode);
  442. return;
  443. }
  444. // Already converted
  445. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  446. callback(preparedSourceCode.replace("#version 300 es", ""));
  447. return;
  448. }
  449. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  450. // Remove extensions
  451. // #extension GL_OES_standard_derivatives : enable
  452. // #extension GL_EXT_shader_texture_lod : enable
  453. // #extension GL_EXT_frag_depth : enable
  454. // #extension GL_EXT_draw_buffers : require
  455. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  456. var result = preparedSourceCode.replace(regex, "");
  457. // Migrate to GLSL v300
  458. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  459. result = result.replace(/attribute[ \t]/g, "in ");
  460. result = result.replace(/[ \t]attribute/g, " in");
  461. if (isFragment) {
  462. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  464. result = result.replace(/texture2D\s*\(/g, "texture(");
  465. result = result.replace(/textureCube\s*\(/g, "texture(");
  466. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  467. result = result.replace(/gl_FragColor/g, "glFragColor");
  468. result = result.replace(/gl_FragData/g, "glFragData");
  469. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  470. }
  471. callback(result);
  472. };
  473. Effect.prototype._processIncludes = function (sourceCode, callback) {
  474. var _this = this;
  475. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  476. var match = regex.exec(sourceCode);
  477. var returnValue = new String(sourceCode);
  478. while (match != null) {
  479. var includeFile = match[1];
  480. // Uniform declaration
  481. if (includeFile.indexOf("__decl__") !== -1) {
  482. includeFile = includeFile.replace(/__decl__/, "");
  483. if (this._engine.supportsUniformBuffers) {
  484. includeFile = includeFile.replace(/Vertex/, "Ubo");
  485. includeFile = includeFile.replace(/Fragment/, "Ubo");
  486. }
  487. includeFile = includeFile + "Declaration";
  488. }
  489. if (Effect.IncludesShadersStore[includeFile]) {
  490. // Substitution
  491. var includeContent = Effect.IncludesShadersStore[includeFile];
  492. if (match[2]) {
  493. var splits = match[3].split(",");
  494. for (var index = 0; index < splits.length; index += 2) {
  495. var source = new RegExp(splits[index], "g");
  496. var dest = splits[index + 1];
  497. includeContent = includeContent.replace(source, dest);
  498. }
  499. }
  500. if (match[4]) {
  501. var indexString = match[5];
  502. if (indexString.indexOf("..") !== -1) {
  503. var indexSplits = indexString.split("..");
  504. var minIndex = parseInt(indexSplits[0]);
  505. var maxIndex = parseInt(indexSplits[1]);
  506. var sourceIncludeContent = includeContent.slice(0);
  507. includeContent = "";
  508. if (isNaN(maxIndex)) {
  509. maxIndex = this._indexParameters[indexSplits[1]];
  510. }
  511. for (var i = minIndex; i < maxIndex; i++) {
  512. if (!this._engine.supportsUniformBuffers) {
  513. // Ubo replacement
  514. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  515. return p1 + "{X}";
  516. });
  517. }
  518. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  519. }
  520. }
  521. else {
  522. if (!this._engine.supportsUniformBuffers) {
  523. // Ubo replacement
  524. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  525. return p1 + "{X}";
  526. });
  527. }
  528. includeContent = includeContent.replace(/\{X\}/g, indexString);
  529. }
  530. }
  531. // Replace
  532. returnValue = returnValue.replace(match[0], includeContent);
  533. }
  534. else {
  535. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  536. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  537. Effect.IncludesShadersStore[includeFile] = fileContent;
  538. _this._processIncludes(returnValue, callback);
  539. });
  540. return;
  541. }
  542. match = regex.exec(sourceCode);
  543. }
  544. callback(returnValue);
  545. };
  546. Effect.prototype._processPrecision = function (source) {
  547. if (source.indexOf("precision highp float") === -1) {
  548. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  549. source = "precision mediump float;\n" + source;
  550. }
  551. else {
  552. source = "precision highp float;\n" + source;
  553. }
  554. }
  555. else {
  556. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  557. source = source.replace("precision highp float", "precision mediump float");
  558. }
  559. }
  560. return source;
  561. };
  562. /**
  563. * Recompiles the webGL program
  564. * @param vertexSourceCode The source code for the vertex shader.
  565. * @param fragmentSourceCode The source code for the fragment shader.
  566. * @param onCompiled Callback called when completed.
  567. * @param onError Callback called on error.
  568. */
  569. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  570. var _this = this;
  571. this._isReady = false;
  572. this._vertexSourceCodeOverride = vertexSourceCode;
  573. this._fragmentSourceCodeOverride = fragmentSourceCode;
  574. this.onError = function (effect, error) {
  575. if (onError) {
  576. onError(error);
  577. }
  578. };
  579. this.onCompiled = function () {
  580. var scenes = _this.getEngine().scenes;
  581. for (var i = 0; i < scenes.length; i++) {
  582. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  583. }
  584. if (onCompiled) {
  585. onCompiled(_this._program);
  586. }
  587. };
  588. this._fallbacks = null;
  589. this._prepareEffect();
  590. };
  591. /**
  592. * Gets the uniform locations of the the specified variable names
  593. * @param names THe names of the variables to lookup.
  594. * @returns Array of locations in the same order as variable names.
  595. */
  596. Effect.prototype.getSpecificUniformLocations = function (names) {
  597. var engine = this._engine;
  598. return engine.getUniforms(this._program, names);
  599. };
  600. /**
  601. * Prepares the effect
  602. */
  603. Effect.prototype._prepareEffect = function () {
  604. var attributesNames = this._attributesNames;
  605. var defines = this.defines;
  606. var fallbacks = this._fallbacks;
  607. this._valueCache = {};
  608. var previousProgram = this._program;
  609. try {
  610. var engine = this._engine;
  611. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  612. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  613. }
  614. else {
  615. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  616. }
  617. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  618. if (engine.supportsUniformBuffers) {
  619. for (var name in this._uniformBuffersNames) {
  620. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  621. }
  622. }
  623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  624. this._attributes = engine.getAttributes(this._program, attributesNames);
  625. var index;
  626. for (index = 0; index < this._samplers.length; index++) {
  627. var sampler = this.getUniform(this._samplers[index]);
  628. if (sampler == null) {
  629. this._samplers.splice(index, 1);
  630. index--;
  631. }
  632. }
  633. engine.bindSamplers(this);
  634. this._compilationError = "";
  635. this._isReady = true;
  636. if (this.onCompiled) {
  637. this.onCompiled(this);
  638. }
  639. this.onCompileObservable.notifyObservers(this);
  640. this.onCompileObservable.clear();
  641. // Unbind mesh reference in fallbacks
  642. if (this._fallbacks) {
  643. this._fallbacks.unBindMesh();
  644. }
  645. if (previousProgram) {
  646. this.getEngine()._deleteProgram(previousProgram);
  647. }
  648. }
  649. catch (e) {
  650. this._compilationError = e.message;
  651. // Let's go through fallbacks then
  652. BABYLON.Tools.Error("Unable to compile effect:");
  653. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  654. return " " + uniform;
  655. }));
  656. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  657. return " " + attribute;
  658. }));
  659. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  660. BABYLON.Tools.Error("Error: " + this._compilationError);
  661. if (previousProgram) {
  662. this._program = previousProgram;
  663. this._isReady = true;
  664. if (this.onError) {
  665. this.onError(this, this._compilationError);
  666. }
  667. this.onErrorObservable.notifyObservers(this);
  668. }
  669. if (fallbacks && fallbacks.isMoreFallbacks) {
  670. BABYLON.Tools.Error("Trying next fallback.");
  671. this.defines = fallbacks.reduce(this.defines, this);
  672. this._prepareEffect();
  673. }
  674. else {
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. this.onErrorObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. }
  685. }
  686. };
  687. Object.defineProperty(Effect.prototype, "isSupported", {
  688. /**
  689. * Checks if the effect is supported. (Must be called after compilation)
  690. */
  691. get: function () {
  692. return this._compilationError === "";
  693. },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. /**
  698. * Binds a texture to the engine to be used as output of the shader.
  699. * @param channel Name of the output variable.
  700. * @param texture Texture to bind.
  701. */
  702. Effect.prototype._bindTexture = function (channel, texture) {
  703. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  704. };
  705. /**
  706. * Sets a texture on the engine to be used in the shader.
  707. * @param channel Name of the sampler variable.
  708. * @param texture Texture to set.
  709. */
  710. Effect.prototype.setTexture = function (channel, texture) {
  711. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  712. };
  713. /**
  714. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  715. * @param channel Name of the sampler variable.
  716. * @param texture Texture to set.
  717. */
  718. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  719. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  720. };
  721. /**
  722. * Sets an array of textures on the engine to be used in the shader.
  723. * @param channel Name of the variable.
  724. * @param textures Textures to set.
  725. */
  726. Effect.prototype.setTextureArray = function (channel, textures) {
  727. if (this._samplers.indexOf(channel + "Ex") === -1) {
  728. var initialPos = this._samplers.indexOf(channel);
  729. for (var index = 1; index < textures.length; index++) {
  730. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  731. }
  732. }
  733. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  734. };
  735. /**
  736. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  737. * @param channel Name of the sampler variable.
  738. * @param postProcess Post process to get the input texture from.
  739. */
  740. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  741. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  742. };
  743. /**
  744. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  745. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  746. * @param channel Name of the sampler variable.
  747. * @param postProcess Post process to get the output texture from.
  748. */
  749. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  750. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  751. };
  752. /** @ignore */
  753. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  754. var cache = this._valueCache[uniformName];
  755. var flag = matrix.updateFlag;
  756. if (cache !== undefined && cache === flag) {
  757. return false;
  758. }
  759. this._valueCache[uniformName] = flag;
  760. return true;
  761. };
  762. /** @ignore */
  763. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  764. var cache = this._valueCache[uniformName];
  765. if (!cache) {
  766. cache = [x, y];
  767. this._valueCache[uniformName] = cache;
  768. return true;
  769. }
  770. var changed = false;
  771. if (cache[0] !== x) {
  772. cache[0] = x;
  773. changed = true;
  774. }
  775. if (cache[1] !== y) {
  776. cache[1] = y;
  777. changed = true;
  778. }
  779. return changed;
  780. };
  781. /** @ignore */
  782. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  783. var cache = this._valueCache[uniformName];
  784. if (!cache) {
  785. cache = [x, y, z];
  786. this._valueCache[uniformName] = cache;
  787. return true;
  788. }
  789. var changed = false;
  790. if (cache[0] !== x) {
  791. cache[0] = x;
  792. changed = true;
  793. }
  794. if (cache[1] !== y) {
  795. cache[1] = y;
  796. changed = true;
  797. }
  798. if (cache[2] !== z) {
  799. cache[2] = z;
  800. changed = true;
  801. }
  802. return changed;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y, z, w];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. if (cache[2] !== z) {
  822. cache[2] = z;
  823. changed = true;
  824. }
  825. if (cache[3] !== w) {
  826. cache[3] = w;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /**
  832. * Binds a buffer to a uniform.
  833. * @param buffer Buffer to bind.
  834. * @param name Name of the uniform variable to bind to.
  835. */
  836. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  837. var bufferName = this._uniformBuffersNames[name];
  838. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  839. return;
  840. }
  841. Effect._baseCache[bufferName] = buffer;
  842. this._engine.bindUniformBufferBase(buffer, bufferName);
  843. };
  844. /**
  845. * Binds block to a uniform.
  846. * @param blockName Name of the block to bind.
  847. * @param index Index to bind.
  848. */
  849. Effect.prototype.bindUniformBlock = function (blockName, index) {
  850. this._engine.bindUniformBlock(this._program, blockName, index);
  851. };
  852. /**
  853. * Sets an interger value on a uniform variable.
  854. * @param uniformName Name of the variable.
  855. * @param value Value to be set.
  856. * @returns this effect.
  857. */
  858. Effect.prototype.setInt = function (uniformName, value) {
  859. var cache = this._valueCache[uniformName];
  860. if (cache !== undefined && cache === value)
  861. return this;
  862. this._valueCache[uniformName] = value;
  863. this._engine.setInt(this.getUniform(uniformName), value);
  864. return this;
  865. };
  866. /**
  867. * Sets an int array on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param array array to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setIntArray = function (uniformName, array) {
  873. this._valueCache[uniformName] = null;
  874. this._engine.setIntArray(this.getUniform(uniformName), array);
  875. return this;
  876. };
  877. /**
  878. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray3 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray3(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray4 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray4(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * Sets an float array on a uniform variable.
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setFloatArray = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setFloatArray(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an array on a uniform variable.
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setArray = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setArray(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray2 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray2(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray3 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray3(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray4 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray4(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets matrices on a uniform variable.
  1000. * @param uniformName Name of the variable.
  1001. * @param matrices matrices to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1005. if (!matrices) {
  1006. return this;
  1007. }
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrix on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrix matrix to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1019. if (this._cacheMatrix(uniformName, matrix)) {
  1020. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1021. }
  1022. return this;
  1023. };
  1024. /**
  1025. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1026. * @param uniformName Name of the variable.
  1027. * @param matrix matrix to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1033. return this;
  1034. };
  1035. /**
  1036. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a float on a uniform variable.
  1048. * @param uniformName Name of the variable.
  1049. * @param value value to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloat = function (uniformName, value) {
  1053. var cache = this._valueCache[uniformName];
  1054. if (cache !== undefined && cache === value)
  1055. return this;
  1056. this._valueCache[uniformName] = value;
  1057. this._engine.setFloat(this.getUniform(uniformName), value);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a boolean on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param bool value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setBool = function (uniformName, bool) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === bool)
  1069. return this;
  1070. this._valueCache[uniformName] = bool;
  1071. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a Vector2 on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param vector2 vector2 to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1081. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1082. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1083. }
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a float2 on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param x First float in float2.
  1090. * @param y Second float in float2.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1094. if (this._cacheFloat2(uniformName, x, y)) {
  1095. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1096. }
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets a Vector3 on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param vector3 Value to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1106. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1107. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float3 on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param x First float in float3.
  1115. * @param y Second float in float3.
  1116. * @param z Third float in float3.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1120. if (this._cacheFloat3(uniformName, x, y, z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector4 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector4 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1132. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1133. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float4 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float4.
  1141. * @param y Second float in float4.
  1142. * @param z Third float in float4.
  1143. * @param w Fourth float in float4.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1147. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1148. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Color3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param color3 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setColor3 = function (uniformName, color3) {
  1159. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1160. this._engine.setColor3(this.getUniform(uniformName), color3);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Color4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param color3 Value to be set.
  1168. * @param alpha Alpha value to be set.
  1169. * @returns this effect.
  1170. */
  1171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1174. }
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Color4 on a uniform variable
  1179. * @param uniformName defines the name of the variable
  1180. * @param color4 defines the value to be set
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1184. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1185. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Resets the cache of effects.
  1191. */
  1192. Effect.ResetCache = function () {
  1193. Effect._baseCache = {};
  1194. };
  1195. Effect._uniqueIdSeed = 0;
  1196. Effect._baseCache = {};
  1197. /**
  1198. * Store of each shader (The can be looked up using effect.key)
  1199. */
  1200. Effect.ShadersStore = {};
  1201. /**
  1202. * Store of each included file for a shader (The can be looked up using effect.key)
  1203. */
  1204. Effect.IncludesShadersStore = {};
  1205. return Effect;
  1206. }());
  1207. BABYLON.Effect = Effect;
  1208. })(BABYLON || (BABYLON = {}));
  1209. //# sourceMappingURL=babylon.effect.js.map
  1210. "use strict";
  1211. //# sourceMappingURL=babylon.types.js.map
  1212. "use strict";
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. "use strict";
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var PointerEventTypes = /** @class */ (function () {
  1265. function PointerEventTypes() {
  1266. }
  1267. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1268. get: function () {
  1269. return PointerEventTypes._POINTERDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1275. get: function () {
  1276. return PointerEventTypes._POINTERUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1282. get: function () {
  1283. return PointerEventTypes._POINTERMOVE;
  1284. },
  1285. enumerable: true,
  1286. configurable: true
  1287. });
  1288. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1289. get: function () {
  1290. return PointerEventTypes._POINTERWHEEL;
  1291. },
  1292. enumerable: true,
  1293. configurable: true
  1294. });
  1295. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1296. get: function () {
  1297. return PointerEventTypes._POINTERPICK;
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1303. get: function () {
  1304. return PointerEventTypes._POINTERTAP;
  1305. },
  1306. enumerable: true,
  1307. configurable: true
  1308. });
  1309. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1310. get: function () {
  1311. return PointerEventTypes._POINTERDOUBLETAP;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. PointerEventTypes._POINTERDOWN = 0x01;
  1317. PointerEventTypes._POINTERUP = 0x02;
  1318. PointerEventTypes._POINTERMOVE = 0x04;
  1319. PointerEventTypes._POINTERWHEEL = 0x08;
  1320. PointerEventTypes._POINTERPICK = 0x10;
  1321. PointerEventTypes._POINTERTAP = 0x20;
  1322. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1323. return PointerEventTypes;
  1324. }());
  1325. BABYLON.PointerEventTypes = PointerEventTypes;
  1326. var PointerInfoBase = /** @class */ (function () {
  1327. function PointerInfoBase(type, event) {
  1328. this.type = type;
  1329. this.event = event;
  1330. }
  1331. return PointerInfoBase;
  1332. }());
  1333. BABYLON.PointerInfoBase = PointerInfoBase;
  1334. /**
  1335. * This class is used to store pointer related info for the onPrePointerObservable event.
  1336. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1337. */
  1338. var PointerInfoPre = /** @class */ (function (_super) {
  1339. __extends(PointerInfoPre, _super);
  1340. function PointerInfoPre(type, event, localX, localY) {
  1341. var _this = _super.call(this, type, event) || this;
  1342. _this.skipOnPointerObservable = false;
  1343. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1344. return _this;
  1345. }
  1346. return PointerInfoPre;
  1347. }(PointerInfoBase));
  1348. BABYLON.PointerInfoPre = PointerInfoPre;
  1349. /**
  1350. * This type contains all the data related to a pointer event in Babylon.js.
  1351. * 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.
  1352. */
  1353. var PointerInfo = /** @class */ (function (_super) {
  1354. __extends(PointerInfo, _super);
  1355. function PointerInfo(type, event, pickInfo) {
  1356. var _this = _super.call(this, type, event) || this;
  1357. _this.pickInfo = pickInfo;
  1358. return _this;
  1359. }
  1360. return PointerInfo;
  1361. }(PointerInfoBase));
  1362. BABYLON.PointerInfo = PointerInfo;
  1363. })(BABYLON || (BABYLON = {}));
  1364. //# sourceMappingURL=babylon.pointerEvents.js.map
  1365. "use strict";
  1366. var BABYLON;
  1367. (function (BABYLON) {
  1368. BABYLON.ToGammaSpace = 1 / 2.2;
  1369. BABYLON.ToLinearSpace = 2.2;
  1370. BABYLON.Epsilon = 0.001;
  1371. /**
  1372. * Class used to hold a RBG color
  1373. */
  1374. var Color3 = /** @class */ (function () {
  1375. /**
  1376. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1377. * @param r defines the red component (between 0 and 1, default is 0)
  1378. * @param g defines the green component (between 0 and 1, default is 0)
  1379. * @param b defines the blue component (between 0 and 1, default is 0)
  1380. */
  1381. function Color3(
  1382. /**
  1383. * Defines the red component (between 0 and 1, default is 0)
  1384. */
  1385. r,
  1386. /**
  1387. * Defines the green component (between 0 and 1, default is 0)
  1388. */
  1389. g,
  1390. /**
  1391. * Defines the blue component (between 0 and 1, default is 0)
  1392. */
  1393. b) {
  1394. if (r === void 0) { r = 0; }
  1395. if (g === void 0) { g = 0; }
  1396. if (b === void 0) { b = 0; }
  1397. this.r = r;
  1398. this.g = g;
  1399. this.b = b;
  1400. }
  1401. /**
  1402. * Creates a string with the Color3 current values
  1403. * @returns the string representation of the Color3 object
  1404. */
  1405. Color3.prototype.toString = function () {
  1406. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1407. };
  1408. /**
  1409. * Returns the string "Color3"
  1410. * @returns "Color3"
  1411. */
  1412. Color3.prototype.getClassName = function () {
  1413. return "Color3";
  1414. };
  1415. /**
  1416. * Compute the Color3 hash code
  1417. * @returns an unique number that can be used to hash Color3 objects
  1418. */
  1419. Color3.prototype.getHashCode = function () {
  1420. var hash = this.r || 0;
  1421. hash = (hash * 397) ^ (this.g || 0);
  1422. hash = (hash * 397) ^ (this.b || 0);
  1423. return hash;
  1424. };
  1425. // Operators
  1426. /**
  1427. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1428. * @param array defines the array where to store the r,g,b components
  1429. * @param index defines an optional index in the target array to define where to start storing values
  1430. * @returns the current Color3 object
  1431. */
  1432. Color3.prototype.toArray = function (array, index) {
  1433. if (index === undefined) {
  1434. index = 0;
  1435. }
  1436. array[index] = this.r;
  1437. array[index + 1] = this.g;
  1438. array[index + 2] = this.b;
  1439. return this;
  1440. };
  1441. /**
  1442. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1443. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1444. * @returns a new {BABYLON.Color4} object
  1445. */
  1446. Color3.prototype.toColor4 = function (alpha) {
  1447. if (alpha === void 0) { alpha = 1; }
  1448. return new Color4(this.r, this.g, this.b, alpha);
  1449. };
  1450. /**
  1451. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1452. * @returns the new array
  1453. */
  1454. Color3.prototype.asArray = function () {
  1455. var result = new Array();
  1456. this.toArray(result, 0);
  1457. return result;
  1458. };
  1459. /**
  1460. * Returns the luminance value
  1461. * @returns a float value
  1462. */
  1463. Color3.prototype.toLuminance = function () {
  1464. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1465. };
  1466. /**
  1467. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1468. * @param otherColor defines the second operand
  1469. * @returns the new Color3 object
  1470. */
  1471. Color3.prototype.multiply = function (otherColor) {
  1472. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1473. };
  1474. /**
  1475. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1476. * @param otherColor defines the second operand
  1477. * @param result defines the Color3 object where to store the result
  1478. * @returns the current Color3
  1479. */
  1480. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1481. result.r = this.r * otherColor.r;
  1482. result.g = this.g * otherColor.g;
  1483. result.b = this.b * otherColor.b;
  1484. return this;
  1485. };
  1486. /**
  1487. * Determines equality between Color3 objects
  1488. * @param otherColor defines the second operand
  1489. * @returns true if the rgb values are equal to the passed ones
  1490. */
  1491. Color3.prototype.equals = function (otherColor) {
  1492. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1493. };
  1494. /**
  1495. * Determines equality between the current Color3 object and a set of r,b,g values
  1496. * @param r defines the red component to check
  1497. * @param g defines the green component to check
  1498. * @param b defines the blue component to check
  1499. * @returns true if the rgb values are equal to the passed ones
  1500. */
  1501. Color3.prototype.equalsFloats = function (r, g, b) {
  1502. return this.r === r && this.g === g && this.b === b;
  1503. };
  1504. /**
  1505. * Multiplies in place each rgb value by scale
  1506. * @param scale defines the scaling factor
  1507. * @returns the updated Color3
  1508. */
  1509. Color3.prototype.scale = function (scale) {
  1510. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1511. };
  1512. /**
  1513. * Multiplies the rgb values by scale and stores the result into "result"
  1514. * @param scale defines the scaling factor
  1515. * @param result defines the Color3 object where to store the result
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.scaleToRef = function (scale, result) {
  1519. result.r = this.r * scale;
  1520. result.g = this.g * scale;
  1521. result.b = this.b * scale;
  1522. return this;
  1523. };
  1524. /**
  1525. * Scale the current Color3 values by a factor and add the result to a given Color3
  1526. * @param scale defines the scale factor
  1527. * @param result defines color to store the result into
  1528. * @returns the unmodified current Color3
  1529. */
  1530. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1531. result.r += this.r * scale;
  1532. result.g += this.g * scale;
  1533. result.b += this.b * scale;
  1534. return this;
  1535. };
  1536. /**
  1537. * Clamps the rgb values by the min and max values and stores the result into "result"
  1538. * @param min defines minimum clamping value (default is 0)
  1539. * @param max defines maximum clamping value (default is 1)
  1540. * @param result defines color to store the result into
  1541. * @returns the original Color3
  1542. */
  1543. Color3.prototype.clampToRef = function (min, max, result) {
  1544. if (min === void 0) { min = 0; }
  1545. if (max === void 0) { max = 1; }
  1546. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1547. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1548. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1549. return this;
  1550. };
  1551. /**
  1552. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1553. * @param otherColor defines the second operand
  1554. * @returns the new Color3
  1555. */
  1556. Color3.prototype.add = function (otherColor) {
  1557. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1558. };
  1559. /**
  1560. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1561. * @param otherColor defines the second operand
  1562. * @param result defines Color3 object to store the result into
  1563. * @returns the unmodified current Color3
  1564. */
  1565. Color3.prototype.addToRef = function (otherColor, result) {
  1566. result.r = this.r + otherColor.r;
  1567. result.g = this.g + otherColor.g;
  1568. result.b = this.b + otherColor.b;
  1569. return this;
  1570. };
  1571. /**
  1572. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3
  1575. */
  1576. Color3.prototype.subtract = function (otherColor) {
  1577. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1578. };
  1579. /**
  1580. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines Color3 object to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.subtractToRef = function (otherColor, result) {
  1586. result.r = this.r - otherColor.r;
  1587. result.g = this.g - otherColor.g;
  1588. result.b = this.b - otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Copy the current object
  1593. * @returns a new Color3 copied the current one
  1594. */
  1595. Color3.prototype.clone = function () {
  1596. return new Color3(this.r, this.g, this.b);
  1597. };
  1598. /**
  1599. * Copies the rgb values from the source in the current Color3
  1600. * @param source defines the source Color3 object
  1601. * @returns the updated Color3 object
  1602. */
  1603. Color3.prototype.copyFrom = function (source) {
  1604. this.r = source.r;
  1605. this.g = source.g;
  1606. this.b = source.b;
  1607. return this;
  1608. };
  1609. /**
  1610. * Updates the Color3 rgb values from the passed floats
  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. * @returns the current Color3 object
  1615. */
  1616. Color3.prototype.copyFromFloats = function (r, g, b) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. return this;
  1621. };
  1622. /**
  1623. * Updates the Color3 rgb values from the passed floats
  1624. * @param r defines the red component to read from
  1625. * @param g defines the green component to read from
  1626. * @param b defines the blue component to read from
  1627. * @returns the current Color3 object
  1628. */
  1629. Color3.prototype.set = function (r, g, b) {
  1630. return this.copyFromFloats(r, g, b);
  1631. };
  1632. /**
  1633. * Compute the Color3 hexadecimal code as a string
  1634. * @returns a string containing the hexadecimal representation of the Color3 object
  1635. */
  1636. Color3.prototype.toHexString = function () {
  1637. var intR = (this.r * 255) | 0;
  1638. var intG = (this.g * 255) | 0;
  1639. var intB = (this.b * 255) | 0;
  1640. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1641. };
  1642. /**
  1643. * Computes a new Color3 converted from the current one to linear space
  1644. * @returns a new Color3 object
  1645. */
  1646. Color3.prototype.toLinearSpace = function () {
  1647. var convertedColor = new Color3();
  1648. this.toLinearSpaceToRef(convertedColor);
  1649. return convertedColor;
  1650. };
  1651. /**
  1652. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1653. * @param convertedColor defines the Color3 object where to store the linear space version
  1654. * @returns the unmodified Color3
  1655. */
  1656. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1657. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1658. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1659. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1660. return this;
  1661. };
  1662. /**
  1663. * Computes a new Color3 converted from the current one to gamma space
  1664. * @returns a new Color3 object
  1665. */
  1666. Color3.prototype.toGammaSpace = function () {
  1667. var convertedColor = new Color3();
  1668. this.toGammaSpaceToRef(convertedColor);
  1669. return convertedColor;
  1670. };
  1671. /**
  1672. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1673. * @param convertedColor defines the Color3 object where to store the gamma space version
  1674. * @returns the unmodified Color3
  1675. */
  1676. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1677. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1678. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1679. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1680. return this;
  1681. };
  1682. // Statics
  1683. /**
  1684. * Creates a new Color3 from the string containing valid hexadecimal values
  1685. * @param hex defines a string containing valid hexadecimal values
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.FromHexString = function (hex) {
  1689. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1690. return new Color3(0, 0, 0);
  1691. }
  1692. var r = parseInt(hex.substring(1, 3), 16);
  1693. var g = parseInt(hex.substring(3, 5), 16);
  1694. var b = parseInt(hex.substring(5, 7), 16);
  1695. return Color3.FromInts(r, g, b);
  1696. };
  1697. /**
  1698. * Creates a new Vector3 from the starting index of the passed array
  1699. * @param array defines the source array
  1700. * @param offset defines an offset in the source array
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.FromArray = function (array, offset) {
  1704. if (offset === void 0) { offset = 0; }
  1705. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1706. };
  1707. /**
  1708. * Creates a new Color3 from integer values (< 256)
  1709. * @param r defines the red component to read from (value between 0 and 255)
  1710. * @param g defines the green component to read from (value between 0 and 255)
  1711. * @param b defines the blue component to read from (value between 0 and 255)
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.FromInts = function (r, g, b) {
  1715. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1716. };
  1717. /**
  1718. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1719. * @param start defines the start Color3 value
  1720. * @param end defines the end Color3 value
  1721. * @param amount defines the gradient value between start and end
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Lerp = function (start, end, amount) {
  1725. var r = start.r + ((end.r - start.r) * amount);
  1726. var g = start.g + ((end.g - start.g) * amount);
  1727. var b = start.b + ((end.b - start.b) * amount);
  1728. return new Color3(r, g, b);
  1729. };
  1730. /**
  1731. * Returns a Color3 value containing a red color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Red = function () { return new Color3(1, 0, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a green color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Green = function () { return new Color3(0, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a blue color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1745. /**
  1746. * Returns a Color3 value containing a black color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Black = function () { return new Color3(0, 0, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a white color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.White = function () { return new Color3(1, 1, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a purple color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1760. /**
  1761. * Returns a Color3 value containing a magenta color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a yellow color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a gray color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1775. /**
  1776. * Returns a Color3 value containing a teal color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1780. /**
  1781. * Returns a Color3 value containing a random color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1785. return Color3;
  1786. }());
  1787. BABYLON.Color3 = Color3;
  1788. /**
  1789. * Class used to hold a RBGA color
  1790. */
  1791. var Color4 = /** @class */ (function () {
  1792. /**
  1793. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1794. * @param r defines the red component (between 0 and 1, default is 0)
  1795. * @param g defines the green component (between 0 and 1, default is 0)
  1796. * @param b defines the blue component (between 0 and 1, default is 0)
  1797. * @param a defines the alpha component (between 0 and 1, default is 1)
  1798. */
  1799. function Color4(
  1800. /**
  1801. * Defines the red component (between 0 and 1, default is 0)
  1802. */
  1803. r,
  1804. /**
  1805. * Defines the green component (between 0 and 1, default is 0)
  1806. */
  1807. g,
  1808. /**
  1809. * Defines the blue component (between 0 and 1, default is 0)
  1810. */
  1811. b,
  1812. /**
  1813. * Defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. a) {
  1816. if (r === void 0) { r = 0; }
  1817. if (g === void 0) { g = 0; }
  1818. if (b === void 0) { b = 0; }
  1819. if (a === void 0) { a = 1; }
  1820. this.r = r;
  1821. this.g = g;
  1822. this.b = b;
  1823. this.a = a;
  1824. }
  1825. // Operators
  1826. /**
  1827. * Adds in place the passed Color4 values to the current Color4 object
  1828. * @param right defines the second operand
  1829. * @returns the current updated Color4 object
  1830. */
  1831. Color4.prototype.addInPlace = function (right) {
  1832. this.r += right.r;
  1833. this.g += right.g;
  1834. this.b += right.b;
  1835. this.a += right.a;
  1836. return this;
  1837. };
  1838. /**
  1839. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1840. * @returns the new array
  1841. */
  1842. Color4.prototype.asArray = function () {
  1843. var result = new Array();
  1844. this.toArray(result, 0);
  1845. return result;
  1846. };
  1847. /**
  1848. * Stores from the starting index in the passed array the Color4 successive values
  1849. * @param array defines the array where to store the r,g,b components
  1850. * @param index defines an optional index in the target array to define where to start storing values
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.toArray = function (array, index) {
  1854. if (index === undefined) {
  1855. index = 0;
  1856. }
  1857. array[index] = this.r;
  1858. array[index + 1] = this.g;
  1859. array[index + 2] = this.b;
  1860. array[index + 3] = this.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.add = function (right) {
  1869. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1870. };
  1871. /**
  1872. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1873. * @param right defines the second operand
  1874. * @returns a new Color4 object
  1875. */
  1876. Color4.prototype.subtract = function (right) {
  1877. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1878. };
  1879. /**
  1880. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1881. * @param right defines the second operand
  1882. * @param result defines the Color4 object where to store the result
  1883. * @returns the current Color4 object
  1884. */
  1885. Color4.prototype.subtractToRef = function (right, result) {
  1886. result.r = this.r - right.r;
  1887. result.g = this.g - right.g;
  1888. result.b = this.b - right.b;
  1889. result.a = this.a - right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 with the current Color4 values multiplied by scale
  1894. * @param scale defines the scaling factor to apply
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.scale = function (scale) {
  1898. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1899. };
  1900. /**
  1901. * Multiplies the current Color4 values by scale and stores the result in "result"
  1902. * @param scale defines the scaling factor to apply
  1903. * @param result defines the Color4 object where to store the result
  1904. * @returns the current unmodified Color4
  1905. */
  1906. Color4.prototype.scaleToRef = function (scale, result) {
  1907. result.r = this.r * scale;
  1908. result.g = this.g * scale;
  1909. result.b = this.b * scale;
  1910. result.a = this.a * scale;
  1911. return this;
  1912. };
  1913. /**
  1914. * Scale the current Color4 values by a factor and add the result to a given Color4
  1915. * @param scale defines the scale factor
  1916. * @param result defines the Color4 object where to store the result
  1917. * @returns the unmodified current Color4
  1918. */
  1919. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1920. result.r += this.r * scale;
  1921. result.g += this.g * scale;
  1922. result.b += this.b * scale;
  1923. result.a += this.a * scale;
  1924. return this;
  1925. };
  1926. /**
  1927. * Clamps the rgb values by the min and max values and stores the result into "result"
  1928. * @param min defines minimum clamping value (default is 0)
  1929. * @param max defines maximum clamping value (default is 1)
  1930. * @param result defines color to store the result into.
  1931. * @returns the cuurent Color4
  1932. */
  1933. Color4.prototype.clampToRef = function (min, max, result) {
  1934. if (min === void 0) { min = 0; }
  1935. if (max === void 0) { max = 1; }
  1936. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1937. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1938. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1939. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1940. return this;
  1941. };
  1942. /**
  1943. * Multipy an Color4 value by another and return a new Color4 object
  1944. * @param color defines the Color4 value to multiply by
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.multiply = function (color) {
  1948. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1949. };
  1950. /**
  1951. * Multipy a Color4 value by another and push the result in a reference value
  1952. * @param color defines the Color4 value to multiply by
  1953. * @param result defines the Color4 to fill the result in
  1954. * @returns the result Color4
  1955. */
  1956. Color4.prototype.multiplyToRef = function (color, result) {
  1957. result.r = this.r * color.r;
  1958. result.g = this.g * color.g;
  1959. result.b = this.b * color.b;
  1960. result.a = this.a * color.a;
  1961. return result;
  1962. };
  1963. /**
  1964. * Creates a string with the Color4 current values
  1965. * @returns the string representation of the Color4 object
  1966. */
  1967. Color4.prototype.toString = function () {
  1968. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1969. };
  1970. /**
  1971. * Returns the string "Color4"
  1972. * @returns "Color4"
  1973. */
  1974. Color4.prototype.getClassName = function () {
  1975. return "Color4";
  1976. };
  1977. /**
  1978. * Compute the Color4 hash code
  1979. * @returns an unique number that can be used to hash Color4 objects
  1980. */
  1981. Color4.prototype.getHashCode = function () {
  1982. var hash = this.r || 0;
  1983. hash = (hash * 397) ^ (this.g || 0);
  1984. hash = (hash * 397) ^ (this.b || 0);
  1985. hash = (hash * 397) ^ (this.a || 0);
  1986. return hash;
  1987. };
  1988. /**
  1989. * Creates a new Color4 copied from the current one
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.clone = function () {
  1993. return new Color4(this.r, this.g, this.b, this.a);
  1994. };
  1995. /**
  1996. * Copies the passed Color4 values into the current one
  1997. * @param source defines the source Color4 object
  1998. * @returns the current updated Color4 object
  1999. */
  2000. Color4.prototype.copyFrom = function (source) {
  2001. this.r = source.r;
  2002. this.g = source.g;
  2003. this.b = source.b;
  2004. this.a = source.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Copies the passed float values into the current one
  2009. * @param r defines the red component to read from
  2010. * @param g defines the green component to read from
  2011. * @param b defines the blue component to read from
  2012. * @param a defines the alpha component to read from
  2013. * @returns the current updated Color4 object
  2014. */
  2015. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2016. this.r = r;
  2017. this.g = g;
  2018. this.b = b;
  2019. this.a = a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Copies the passed float values into the current one
  2024. * @param r defines the red component to read from
  2025. * @param g defines the green component to read from
  2026. * @param b defines the blue component to read from
  2027. * @param a defines the alpha component to read from
  2028. * @returns the current updated Color4 object
  2029. */
  2030. Color4.prototype.set = function (r, g, b, a) {
  2031. return this.copyFromFloats(r, g, b, a);
  2032. };
  2033. /**
  2034. * Compute the Color4 hexadecimal code as a string
  2035. * @returns a string containing the hexadecimal representation of the Color4 object
  2036. */
  2037. Color4.prototype.toHexString = function () {
  2038. var intR = (this.r * 255) | 0;
  2039. var intG = (this.g * 255) | 0;
  2040. var intB = (this.b * 255) | 0;
  2041. var intA = (this.a * 255) | 0;
  2042. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to linear space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toLinearSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toLinearSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the linear space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Computes a new Color4 converted from the current one to gamma space
  2067. * @returns a new Color4 object
  2068. */
  2069. Color4.prototype.toGammaSpace = function () {
  2070. var convertedColor = new Color4();
  2071. this.toGammaSpaceToRef(convertedColor);
  2072. return convertedColor;
  2073. };
  2074. /**
  2075. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2076. * @param convertedColor defines the Color4 object where to store the gamma space version
  2077. * @returns the unmodified Color4
  2078. */
  2079. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2080. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2081. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2082. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2083. convertedColor.a = this.a;
  2084. return this;
  2085. };
  2086. // Statics
  2087. /**
  2088. * Creates a new Color4 from the string containing valid hexadecimal values
  2089. * @param hex defines a string containing valid hexadecimal values
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.FromHexString = function (hex) {
  2093. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2094. return new Color4(0.0, 0.0, 0.0, 0.0);
  2095. }
  2096. var r = parseInt(hex.substring(1, 3), 16);
  2097. var g = parseInt(hex.substring(3, 5), 16);
  2098. var b = parseInt(hex.substring(5, 7), 16);
  2099. var a = parseInt(hex.substring(7, 9), 16);
  2100. return Color4.FromInts(r, g, b, a);
  2101. };
  2102. /**
  2103. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2104. * @param left defines the start value
  2105. * @param right defines the end value
  2106. * @param amount defines the gradient factor
  2107. * @returns a new Color4 object
  2108. */
  2109. Color4.Lerp = function (left, right, amount) {
  2110. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2111. Color4.LerpToRef(left, right, amount, result);
  2112. return result;
  2113. };
  2114. /**
  2115. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2116. * @param left defines the start value
  2117. * @param right defines the end value
  2118. * @param amount defines the gradient factor
  2119. * @param result defines the Color4 object where to store data
  2120. */
  2121. Color4.LerpToRef = function (left, right, amount, result) {
  2122. result.r = left.r + (right.r - left.r) * amount;
  2123. result.g = left.g + (right.g - left.g) * amount;
  2124. result.b = left.b + (right.b - left.b) * amount;
  2125. result.a = left.a + (right.a - left.a) * amount;
  2126. };
  2127. /**
  2128. * Creates a new Color4 from the starting index element of the passed array
  2129. * @param array defines the source array to read from
  2130. * @param offset defines the offset in the source array
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromArray = function (array, offset) {
  2134. if (offset === void 0) { offset = 0; }
  2135. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2136. };
  2137. /**
  2138. * Creates a new Color3 from integer values (< 256)
  2139. * @param r defines the red component to read from (value between 0 and 255)
  2140. * @param g defines the green component to read from (value between 0 and 255)
  2141. * @param b defines the blue component to read from (value between 0 and 255)
  2142. * @param a defines the alpha component to read from (value between 0 and 255)
  2143. * @returns a new Color3 object
  2144. */
  2145. Color4.FromInts = function (r, g, b, a) {
  2146. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2147. };
  2148. /**
  2149. * Check the content of a given array and convert it to an array containing RGBA data
  2150. * If the original array was already containing count * 4 values then it is returned directly
  2151. * @param colors defines the array to check
  2152. * @param count defines the number of RGBA data to expect
  2153. * @returns an array containing count * 4 values (RGBA)
  2154. */
  2155. Color4.CheckColors4 = function (colors, count) {
  2156. // Check if color3 was used
  2157. if (colors.length === count * 3) {
  2158. var colors4 = [];
  2159. for (var index = 0; index < colors.length; index += 3) {
  2160. var newIndex = (index / 3) * 4;
  2161. colors4[newIndex] = colors[index];
  2162. colors4[newIndex + 1] = colors[index + 1];
  2163. colors4[newIndex + 2] = colors[index + 2];
  2164. colors4[newIndex + 3] = 1.0;
  2165. }
  2166. return colors4;
  2167. }
  2168. return colors;
  2169. };
  2170. return Color4;
  2171. }());
  2172. BABYLON.Color4 = Color4;
  2173. var Vector2 = /** @class */ (function () {
  2174. /**
  2175. * Creates a new Vector2 from the passed x and y coordinates.
  2176. */
  2177. function Vector2(x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. }
  2181. /**
  2182. * Returns a string with the Vector2 coordinates.
  2183. */
  2184. Vector2.prototype.toString = function () {
  2185. return "{X: " + this.x + " Y:" + this.y + "}";
  2186. };
  2187. /**
  2188. * Returns the string "Vector2"
  2189. */
  2190. Vector2.prototype.getClassName = function () {
  2191. return "Vector2";
  2192. };
  2193. /**
  2194. * Returns the Vector2 hash code as a number.
  2195. */
  2196. Vector2.prototype.getHashCode = function () {
  2197. var hash = this.x || 0;
  2198. hash = (hash * 397) ^ (this.y || 0);
  2199. return hash;
  2200. };
  2201. // Operators
  2202. /**
  2203. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2204. * Returns the Vector2.
  2205. */
  2206. Vector2.prototype.toArray = function (array, index) {
  2207. if (index === void 0) { index = 0; }
  2208. array[index] = this.x;
  2209. array[index + 1] = this.y;
  2210. return this;
  2211. };
  2212. /**
  2213. * Returns a new array with 2 elements : the Vector2 coordinates.
  2214. */
  2215. Vector2.prototype.asArray = function () {
  2216. var result = new Array();
  2217. this.toArray(result, 0);
  2218. return result;
  2219. };
  2220. /**
  2221. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2222. * Returns the updated Vector2.
  2223. */
  2224. Vector2.prototype.copyFrom = function (source) {
  2225. this.x = source.x;
  2226. this.y = source.y;
  2227. return this;
  2228. };
  2229. /**
  2230. * Sets the Vector2 coordinates with the passed floats.
  2231. * Returns the updated Vector2.
  2232. */
  2233. Vector2.prototype.copyFromFloats = function (x, y) {
  2234. this.x = x;
  2235. this.y = y;
  2236. return this;
  2237. };
  2238. /**
  2239. * Sets the Vector2 coordinates with the passed floats.
  2240. * Returns the updated Vector2.
  2241. */
  2242. Vector2.prototype.set = function (x, y) {
  2243. return this.copyFromFloats(x, y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2247. */
  2248. Vector2.prototype.add = function (otherVector) {
  2249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.addToRef = function (otherVector, result) {
  2256. result.x = this.x + otherVector.x;
  2257. result.y = this.y + otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.addInPlace = function (otherVector) {
  2265. this.x += otherVector.x;
  2266. this.y += otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2271. */
  2272. Vector2.prototype.addVector3 = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2277. */
  2278. Vector2.prototype.subtract = function (otherVector) {
  2279. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2280. };
  2281. /**
  2282. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2283. * Returns the Vector2.
  2284. */
  2285. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2286. result.x = this.x - otherVector.x;
  2287. result.y = this.y - otherVector.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2292. * Returns the updated Vector2.
  2293. */
  2294. Vector2.prototype.subtractInPlace = function (otherVector) {
  2295. this.x -= otherVector.x;
  2296. this.y -= otherVector.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2304. this.x *= otherVector.x;
  2305. this.y *= otherVector.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2310. */
  2311. Vector2.prototype.multiply = function (otherVector) {
  2312. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2313. };
  2314. /**
  2315. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2319. result.x = this.x * otherVector.x;
  2320. result.y = this.y * otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2325. */
  2326. Vector2.prototype.multiplyByFloats = function (x, y) {
  2327. return new Vector2(this.x * x, this.y * y);
  2328. };
  2329. /**
  2330. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2331. */
  2332. Vector2.prototype.divide = function (otherVector) {
  2333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2337. * Returns the Vector2.
  2338. */
  2339. Vector2.prototype.divideToRef = function (otherVector, result) {
  2340. result.x = this.x / otherVector.x;
  2341. result.y = this.y / otherVector.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Divides the current Vector3 coordinates by the passed ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector2.prototype.divideInPlace = function (otherVector) {
  2349. return this.divideToRef(otherVector, this);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 with current Vector2 negated coordinates.
  2353. */
  2354. Vector2.prototype.negate = function () {
  2355. return new Vector2(-this.x, -this.y);
  2356. };
  2357. /**
  2358. * Multiply the Vector2 coordinates by scale.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.scaleInPlace = function (scale) {
  2362. this.x *= scale;
  2363. this.y *= scale;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2368. */
  2369. Vector2.prototype.scale = function (scale) {
  2370. var result = new Vector2(0, 0);
  2371. this.scaleToRef(scale, result);
  2372. return result;
  2373. };
  2374. /**
  2375. * Scale the current Vector2 values by a factor to a given Vector2
  2376. * @param scale defines the scale factor
  2377. * @param result defines the Vector2 object where to store the result
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.scaleToRef = function (scale, result) {
  2381. result.x = this.x * scale;
  2382. result.y = this.y * scale;
  2383. return this;
  2384. };
  2385. /**
  2386. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2387. * @param scale defines the scale factor
  2388. * @param result defines the Vector2 object where to store the result
  2389. * @returns the unmodified current Vector2
  2390. */
  2391. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2392. result.x += this.x * scale;
  2393. result.y += this.y * scale;
  2394. return this;
  2395. };
  2396. /**
  2397. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2398. */
  2399. Vector2.prototype.equals = function (otherVector) {
  2400. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2401. };
  2402. /**
  2403. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2404. */
  2405. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2406. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2407. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2408. };
  2409. // Properties
  2410. /**
  2411. * Returns the vector length (float).
  2412. */
  2413. Vector2.prototype.length = function () {
  2414. return Math.sqrt(this.x * this.x + this.y * this.y);
  2415. };
  2416. /**
  2417. * Returns the vector squared length (float);
  2418. */
  2419. Vector2.prototype.lengthSquared = function () {
  2420. return (this.x * this.x + this.y * this.y);
  2421. };
  2422. // Methods
  2423. /**
  2424. * Normalize the vector.
  2425. * Returns the updated Vector2.
  2426. */
  2427. Vector2.prototype.normalize = function () {
  2428. var len = this.length();
  2429. if (len === 0)
  2430. return this;
  2431. var num = 1.0 / len;
  2432. this.x *= num;
  2433. this.y *= num;
  2434. return this;
  2435. };
  2436. /**
  2437. * Returns a new Vector2 copied from the Vector2.
  2438. */
  2439. Vector2.prototype.clone = function () {
  2440. return new Vector2(this.x, this.y);
  2441. };
  2442. // Statics
  2443. /**
  2444. * Returns a new Vector2(0, 0)
  2445. */
  2446. Vector2.Zero = function () {
  2447. return new Vector2(0, 0);
  2448. };
  2449. /**
  2450. * Returns a new Vector2(1, 1)
  2451. */
  2452. Vector2.One = function () {
  2453. return new Vector2(1, 1);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set from the passed index element of the passed array.
  2457. */
  2458. Vector2.FromArray = function (array, offset) {
  2459. if (offset === void 0) { offset = 0; }
  2460. return new Vector2(array[offset], array[offset + 1]);
  2461. };
  2462. /**
  2463. * Sets "result" from the passed index element of the passed array.
  2464. */
  2465. Vector2.FromArrayToRef = function (array, offset, result) {
  2466. result.x = array[offset];
  2467. result.y = array[offset + 1];
  2468. };
  2469. /**
  2470. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2471. */
  2472. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2473. var squared = amount * amount;
  2474. var cubed = amount * squared;
  2475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * 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".
  2485. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2486. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2487. */
  2488. Vector2.Clamp = function (value, min, max) {
  2489. var x = value.x;
  2490. x = (x > max.x) ? max.x : x;
  2491. x = (x < min.x) ? min.x : x;
  2492. var y = value.y;
  2493. y = (y > max.y) ? max.y : y;
  2494. y = (y < min.y) ? min.y : y;
  2495. return new Vector2(x, y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2499. */
  2500. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2501. var squared = amount * amount;
  2502. var cubed = amount * squared;
  2503. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2504. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2505. var part3 = (cubed - (2.0 * squared)) + amount;
  2506. var part4 = cubed - squared;
  2507. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2508. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2509. return new Vector2(x, y);
  2510. };
  2511. /**
  2512. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2513. */
  2514. Vector2.Lerp = function (start, end, amount) {
  2515. var x = start.x + ((end.x - start.x) * amount);
  2516. var y = start.y + ((end.y - start.y) * amount);
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns the dot product (float) of the vector "left" and the vector "right".
  2521. */
  2522. Vector2.Dot = function (left, right) {
  2523. return left.x * right.x + left.y * right.y;
  2524. };
  2525. /**
  2526. * Returns a new Vector2 equal to the normalized passed vector.
  2527. */
  2528. Vector2.Normalize = function (vector) {
  2529. var newVector = vector.clone();
  2530. newVector.normalize();
  2531. return newVector;
  2532. };
  2533. /**
  2534. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2535. */
  2536. Vector2.Minimize = function (left, right) {
  2537. var x = (left.x < right.x) ? left.x : right.x;
  2538. var y = (left.y < right.y) ? left.y : right.y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2543. */
  2544. Vector2.Maximize = function (left, right) {
  2545. var x = (left.x > right.x) ? left.x : right.x;
  2546. var y = (left.y > right.y) ? left.y : right.y;
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2551. */
  2552. Vector2.Transform = function (vector, transformation) {
  2553. var r = Vector2.Zero();
  2554. Vector2.TransformToRef(vector, transformation, r);
  2555. return r;
  2556. };
  2557. /**
  2558. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2559. */
  2560. Vector2.TransformToRef = function (vector, transformation, result) {
  2561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2563. result.x = x;
  2564. result.y = y;
  2565. };
  2566. /**
  2567. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2568. */
  2569. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2570. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2571. var sign = a < 0 ? -1 : 1;
  2572. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2573. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2574. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2575. };
  2576. /**
  2577. * Returns the distance (float) between the vectors "value1" and "value2".
  2578. */
  2579. Vector2.Distance = function (value1, value2) {
  2580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2581. };
  2582. /**
  2583. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2584. */
  2585. Vector2.DistanceSquared = function (value1, value2) {
  2586. var x = value1.x - value2.x;
  2587. var y = value1.y - value2.y;
  2588. return (x * x) + (y * y);
  2589. };
  2590. /**
  2591. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2592. */
  2593. Vector2.Center = function (value1, value2) {
  2594. var center = value1.add(value2);
  2595. center.scaleInPlace(0.5);
  2596. return center;
  2597. };
  2598. /**
  2599. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2600. */
  2601. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2602. var l2 = Vector2.DistanceSquared(segA, segB);
  2603. if (l2 === 0.0) {
  2604. return Vector2.Distance(p, segA);
  2605. }
  2606. var v = segB.subtract(segA);
  2607. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2608. var proj = segA.add(v.multiplyByFloats(t, t));
  2609. return Vector2.Distance(p, proj);
  2610. };
  2611. return Vector2;
  2612. }());
  2613. BABYLON.Vector2 = Vector2;
  2614. /**
  2615. * Classed used to store (x,y,z) vector representation
  2616. * A Vector3 is the main object used in 3D geometry
  2617. * It can represent etiher the coordinates of a point the space, either a direction
  2618. * Reminder: Babylon.js uses a left handed forward facing system
  2619. */
  2620. var Vector3 = /** @class */ (function () {
  2621. /**
  2622. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2623. * @param x defines the first coordinates (on X axis)
  2624. * @param y defines the second coordinates (on Y axis)
  2625. * @param z defines the third coordinates (on Z axis)
  2626. */
  2627. function Vector3(
  2628. /**
  2629. * Defines the first coordinates (on X axis)
  2630. */
  2631. x,
  2632. /**
  2633. * Defines the second coordinates (on Y axis)
  2634. */
  2635. y,
  2636. /**
  2637. * Defines the third coordinates (on Z axis)
  2638. */
  2639. z) {
  2640. this.x = x;
  2641. this.y = y;
  2642. this.z = z;
  2643. }
  2644. /**
  2645. * Creates a string representation of the Vector3
  2646. * @returns a string with the Vector3 coordinates.
  2647. */
  2648. Vector3.prototype.toString = function () {
  2649. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2650. };
  2651. /**
  2652. * Gets the class name
  2653. * @returns the string "Vector3"
  2654. */
  2655. Vector3.prototype.getClassName = function () {
  2656. return "Vector3";
  2657. };
  2658. /**
  2659. * Creates the Vector3 hash code
  2660. * @returns a number which tends to be unique between Vector3 instances
  2661. */
  2662. Vector3.prototype.getHashCode = function () {
  2663. var hash = this.x || 0;
  2664. hash = (hash * 397) ^ (this.y || 0);
  2665. hash = (hash * 397) ^ (this.z || 0);
  2666. return hash;
  2667. };
  2668. // Operators
  2669. /**
  2670. * Creates an array containing three elements : the coordinates of the Vector3
  2671. * @returns a new array of numbers
  2672. */
  2673. Vector3.prototype.asArray = function () {
  2674. var result = [];
  2675. this.toArray(result, 0);
  2676. return result;
  2677. };
  2678. /**
  2679. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2680. * @param array defines the destination array
  2681. * @param index defines the offset in the destination array
  2682. * @returns the current Vector3
  2683. */
  2684. Vector3.prototype.toArray = function (array, index) {
  2685. if (index === void 0) { index = 0; }
  2686. array[index] = this.x;
  2687. array[index + 1] = this.y;
  2688. array[index + 2] = this.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2693. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2694. */
  2695. Vector3.prototype.toQuaternion = function () {
  2696. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2697. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2698. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2699. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2700. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2701. var cosy = Math.cos(this.y * 0.5);
  2702. var siny = Math.sin(this.y * 0.5);
  2703. result.x = coszMinusx * siny;
  2704. result.y = -sinzMinusx * siny;
  2705. result.z = sinxPlusz * cosy;
  2706. result.w = cosxPlusz * cosy;
  2707. return result;
  2708. };
  2709. /**
  2710. * Adds the passed vector to the current Vector3
  2711. * @param otherVector defines the second operand
  2712. * @returns the current updated Vector3
  2713. */
  2714. Vector3.prototype.addInPlace = function (otherVector) {
  2715. this.x += otherVector.x;
  2716. this.y += otherVector.y;
  2717. this.z += otherVector.z;
  2718. return this;
  2719. };
  2720. /**
  2721. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2722. * @param otherVector defines the second operand
  2723. * @returns the resulting Vector3
  2724. */
  2725. Vector3.prototype.add = function (otherVector) {
  2726. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2727. };
  2728. /**
  2729. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2730. * @param otherVector defines the second operand
  2731. * @param result defines the Vector3 object where to store the result
  2732. * @returns the current Vector3
  2733. */
  2734. Vector3.prototype.addToRef = function (otherVector, result) {
  2735. result.x = this.x + otherVector.x;
  2736. result.y = this.y + otherVector.y;
  2737. result.z = this.z + otherVector.z;
  2738. return this;
  2739. };
  2740. /**
  2741. * Subtract the passed vector from the current Vector3
  2742. * @param otherVector defines the second operand
  2743. * @returns the current updated Vector3
  2744. */
  2745. Vector3.prototype.subtractInPlace = function (otherVector) {
  2746. this.x -= otherVector.x;
  2747. this.y -= otherVector.y;
  2748. this.z -= otherVector.z;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2753. * @param otherVector defines the second operand
  2754. * @returns the resulting Vector3
  2755. */
  2756. Vector3.prototype.subtract = function (otherVector) {
  2757. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2758. };
  2759. /**
  2760. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2761. * @param otherVector defines the second operand
  2762. * @param result defines the Vector3 object where to store the result
  2763. * @returns the current Vector3
  2764. */
  2765. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2766. result.x = this.x - otherVector.x;
  2767. result.y = this.y - otherVector.y;
  2768. result.z = this.z - otherVector.z;
  2769. return this;
  2770. };
  2771. /**
  2772. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2779. return new Vector3(this.x - x, this.y - y, this.z - z);
  2780. };
  2781. /**
  2782. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2790. result.x = this.x - x;
  2791. result.y = this.y - y;
  2792. result.z = this.z - z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2797. * @returns a new Vector3
  2798. */
  2799. Vector3.prototype.negate = function () {
  2800. return new Vector3(-this.x, -this.y, -this.z);
  2801. };
  2802. /**
  2803. * Multiplies the Vector3 coordinates by the float "scale"
  2804. * @param scale defines the multiplier factor
  2805. * @returns the current updated Vector3
  2806. */
  2807. Vector3.prototype.scaleInPlace = function (scale) {
  2808. this.x *= scale;
  2809. this.y *= scale;
  2810. this.z *= scale;
  2811. return this;
  2812. };
  2813. /**
  2814. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2815. * @param scale defines the multiplier factor
  2816. * @returns a new Vector3
  2817. */
  2818. Vector3.prototype.scale = function (scale) {
  2819. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2820. };
  2821. /**
  2822. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2823. * @param scale defines the multiplier factor
  2824. * @param result defines the Vector3 object where to store the result
  2825. * @returns the current Vector3
  2826. */
  2827. Vector3.prototype.scaleToRef = function (scale, result) {
  2828. result.x = this.x * scale;
  2829. result.y = this.y * scale;
  2830. result.z = this.z * scale;
  2831. return this;
  2832. };
  2833. /**
  2834. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2835. * @param scale defines the scale factor
  2836. * @param result defines the Vector3 object where to store the result
  2837. * @returns the unmodified current Vector3
  2838. */
  2839. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2840. result.x += this.x * scale;
  2841. result.y += this.y * scale;
  2842. result.z += this.z * scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2847. * @param otherVector defines the second operand
  2848. * @returns true if both vectors are equals
  2849. */
  2850. Vector3.prototype.equals = function (otherVector) {
  2851. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2852. };
  2853. /**
  2854. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2855. * @param otherVector defines the second operand
  2856. * @param epsilon defines the minimal distance to define values as equals
  2857. * @returns true if both vectors are distant less than epsilon
  2858. */
  2859. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2861. 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);
  2862. };
  2863. /**
  2864. * Returns true if the current Vector3 coordinates equals the passed floats
  2865. * @param x defines the x coordinate of the operand
  2866. * @param y defines the y coordinate of the operand
  2867. * @param z defines the z coordinate of the operand
  2868. * @returns true if both vectors are equals
  2869. */
  2870. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2871. return this.x === x && this.y === y && this.z === z;
  2872. };
  2873. /**
  2874. * Multiplies the current Vector3 coordinates by the passed ones
  2875. * @param otherVector defines the second operand
  2876. * @returns the current updated Vector3
  2877. */
  2878. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. return this;
  2883. };
  2884. /**
  2885. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2886. * @param otherVector defines the second operand
  2887. * @returns the new Vector3
  2888. */
  2889. Vector3.prototype.multiply = function (otherVector) {
  2890. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2891. };
  2892. /**
  2893. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2894. * @param otherVector defines the second operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2899. result.x = this.x * otherVector.x;
  2900. result.y = this.y * otherVector.y;
  2901. result.z = this.z * otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2906. * @param x defines the x coordinate of the operand
  2907. * @param y defines the y coordinate of the operand
  2908. * @param z defines the z coordinate of the operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2912. return new Vector3(this.x * x, this.y * y, this.z * z);
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2916. * @param otherVector defines the second operand
  2917. * @returns the new Vector3
  2918. */
  2919. Vector3.prototype.divide = function (otherVector) {
  2920. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2921. };
  2922. /**
  2923. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2924. * @param otherVector defines the second operand
  2925. * @param result defines the Vector3 object where to store the result
  2926. * @returns the current Vector3
  2927. */
  2928. Vector3.prototype.divideToRef = function (otherVector, result) {
  2929. result.x = this.x / otherVector.x;
  2930. result.y = this.y / otherVector.y;
  2931. result.z = this.z / otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.divideInPlace = function (otherVector) {
  2940. return this.divideToRef(otherVector, this);
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.minimizeInPlace = function (other) {
  2948. if (other.x < this.x)
  2949. this.x = other.x;
  2950. if (other.y < this.y)
  2951. this.y = other.y;
  2952. if (other.z < this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2958. * @param other defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.maximizeInPlace = function (other) {
  2962. if (other.x > this.x)
  2963. this.x = other.x;
  2964. if (other.y > this.y)
  2965. this.y = other.y;
  2966. if (other.z > this.z)
  2967. this.z = other.z;
  2968. return this;
  2969. };
  2970. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2971. /**
  2972. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2973. */
  2974. get: function () {
  2975. var absX = Math.abs(this.x);
  2976. var absY = Math.abs(this.y);
  2977. if (absX !== absY) {
  2978. return true;
  2979. }
  2980. var absZ = Math.abs(this.z);
  2981. if (absX !== absZ) {
  2982. return true;
  2983. }
  2984. if (absY !== absZ) {
  2985. return true;
  2986. }
  2987. return false;
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. // Properties
  2993. /**
  2994. * Gets the length of the Vector3
  2995. * @returns the length of the Vecto3
  2996. */
  2997. Vector3.prototype.length = function () {
  2998. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2999. };
  3000. /**
  3001. * Gets the squared length of the Vector3
  3002. * @returns squared length of the Vector3
  3003. */
  3004. Vector3.prototype.lengthSquared = function () {
  3005. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3006. };
  3007. /**
  3008. * Normalize the current Vector3.
  3009. * Please note that this is an in place operation.
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.normalize = function () {
  3013. var len = this.length();
  3014. if (len === 0 || len === 1.0)
  3015. return this;
  3016. var num = 1.0 / len;
  3017. this.x *= num;
  3018. this.y *= num;
  3019. this.z *= num;
  3020. return this;
  3021. };
  3022. /**
  3023. * Normalize the current Vector3 to a new vector
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.normalizeToNew = function () {
  3027. var normalized = new Vector3(0, 0, 0);
  3028. this.normalizeToRef(normalized);
  3029. return normalized;
  3030. };
  3031. /**
  3032. * Normalize the current Vector3 to the reference
  3033. * @param reference define the Vector3 to update
  3034. * @returns the updated Vector3
  3035. */
  3036. Vector3.prototype.normalizeToRef = function (reference) {
  3037. var len = this.length();
  3038. if (len === 0 || len === 1.0) {
  3039. reference.set(this.x, this.y, this.z);
  3040. return reference;
  3041. }
  3042. var scale = 1.0 / len;
  3043. this.scaleToRef(scale, reference);
  3044. return reference;
  3045. };
  3046. /**
  3047. * Creates a new Vector3 copied from the current Vector3
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.clone = function () {
  3051. return new Vector3(this.x, this.y, this.z);
  3052. };
  3053. /**
  3054. * Copies the passed vector coordinates to the current Vector3 ones
  3055. * @param source defines the source Vector3
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.copyFrom = function (source) {
  3059. this.x = source.x;
  3060. this.y = source.y;
  3061. this.z = source.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Copies the passed floats to the current Vector3 coordinates
  3066. * @param x defines the x coordinate of the operand
  3067. * @param y defines the y coordinate of the operand
  3068. * @param z defines the z coordinate of the operand
  3069. * @returns the current updated Vector3
  3070. */
  3071. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3072. this.x = x;
  3073. this.y = y;
  3074. this.z = z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Copies the passed floats to the current Vector3 coordinates
  3079. * @param x defines the x coordinate of the operand
  3080. * @param y defines the y coordinate of the operand
  3081. * @param z defines the z coordinate of the operand
  3082. * @returns the current updated Vector3
  3083. */
  3084. Vector3.prototype.set = function (x, y, z) {
  3085. return this.copyFromFloats(x, y, z);
  3086. };
  3087. // Statics
  3088. /**
  3089. * Get the clip factor between two vectors
  3090. * @param vector0 defines the first operand
  3091. * @param vector1 defines the second operand
  3092. * @param axis defines the axis to use
  3093. * @param size defines the size along the axis
  3094. * @returns the clip factor
  3095. */
  3096. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3097. var d0 = Vector3.Dot(vector0, axis) - size;
  3098. var d1 = Vector3.Dot(vector1, axis) - size;
  3099. var s = d0 / (d0 - d1);
  3100. return s;
  3101. };
  3102. /**
  3103. * Get angle between two vectors
  3104. * @param vector0 angle between vector0 and vector1
  3105. * @param vector1 angle between vector0 and vector1
  3106. * @param normal direction of the normal
  3107. * @return the angle between vector0 and vector1
  3108. */
  3109. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3110. var v0 = vector0.clone().normalize();
  3111. var v1 = vector1.clone().normalize();
  3112. var dot = Vector3.Dot(v0, v1);
  3113. var n = Vector3.Cross(v0, v1);
  3114. if (Vector3.Dot(n, normal) > 0) {
  3115. return Math.acos(dot);
  3116. }
  3117. return -Math.acos(dot);
  3118. };
  3119. /**
  3120. * Returns a new Vector3 set from the index "offset" of the passed array
  3121. * @param array defines the source array
  3122. * @param offset defines the offset in the source array
  3123. * @returns the new Vector3
  3124. */
  3125. Vector3.FromArray = function (array, offset) {
  3126. if (!offset) {
  3127. offset = 0;
  3128. }
  3129. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3133. * This function is deprecated. Use FromArray instead
  3134. * @param array defines the source array
  3135. * @param offset defines the offset in the source array
  3136. * @returns the new Vector3
  3137. */
  3138. Vector3.FromFloatArray = function (array, offset) {
  3139. return Vector3.FromArray(array, offset);
  3140. };
  3141. /**
  3142. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @param result defines the Vector3 where to store the result
  3146. */
  3147. Vector3.FromArrayToRef = function (array, offset, result) {
  3148. result.x = array[offset];
  3149. result.y = array[offset + 1];
  3150. result.z = array[offset + 2];
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3154. * This function is deprecated. Use FromArrayToRef instead.
  3155. * @param array defines the source array
  3156. * @param offset defines the offset in the source array
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3160. return Vector3.FromArrayToRef(array, offset, result);
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" with the passed floats.
  3164. * @param x defines the x coordinate of the source
  3165. * @param y defines the y coordinate of the source
  3166. * @param z defines the z coordinate of the source
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3170. result.x = x;
  3171. result.y = y;
  3172. result.z = z;
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3176. * @returns a new empty Vector3
  3177. */
  3178. Vector3.Zero = function () {
  3179. return new Vector3(0.0, 0.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3183. * @returns a new unit Vector3
  3184. */
  3185. Vector3.One = function () {
  3186. return new Vector3(1.0, 1.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3190. * @returns a new up Vector3
  3191. */
  3192. Vector3.Up = function () {
  3193. return new Vector3(0.0, 1.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3197. * @returns a new forward Vector3
  3198. */
  3199. Vector3.Forward = function () {
  3200. return new Vector3(0.0, 0.0, 1.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3204. * @returns a new right Vector3
  3205. */
  3206. Vector3.Right = function () {
  3207. return new Vector3(1.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3211. * @returns a new left Vector3
  3212. */
  3213. Vector3.Left = function () {
  3214. return new Vector3(-1.0, 0.0, 0.0);
  3215. };
  3216. /**
  3217. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3218. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3219. * @param vector defines the Vector3 to transform
  3220. * @param transformation defines the transformation matrix
  3221. * @returns the transformed Vector3
  3222. */
  3223. Vector3.TransformCoordinates = function (vector, transformation) {
  3224. var result = Vector3.Zero();
  3225. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3230. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3231. * @param vector defines the Vector3 to transform
  3232. * @param transformation defines the transformation matrix
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3239. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3240. result.x = x / w;
  3241. result.y = y / w;
  3242. result.z = z / w;
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3246. * This method computes tranformed coordinates only, not transformed direction vectors
  3247. * @param x define the x coordinate of the source vector
  3248. * @param y define the y coordinate of the source vector
  3249. * @param z define the z coordinate of the source vector
  3250. * @param transformation defines the transformation matrix
  3251. * @param result defines the Vector3 where to store the result
  3252. */
  3253. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3254. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3255. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3256. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3257. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3258. result.x = rx / rw;
  3259. result.y = ry / rw;
  3260. result.z = rz / rw;
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3264. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3265. * @param vector defines the Vector3 to transform
  3266. * @param transformation defines the transformation matrix
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.TransformNormal = function (vector, transformation) {
  3270. var result = Vector3.Zero();
  3271. Vector3.TransformNormalToRef(vector, transformation, result);
  3272. return result;
  3273. };
  3274. /**
  3275. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3276. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3277. * @param vector defines the Vector3 to transform
  3278. * @param transformation defines the transformation matrix
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param x define the x coordinate of the source vector
  3293. * @param y define the y coordinate of the source vector
  3294. * @param z define the z coordinate of the source vector
  3295. * @param transformation defines the transformation matrix
  3296. * @param result defines the Vector3 where to store the result
  3297. */
  3298. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3299. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3300. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3301. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3305. * @param value1 defines the first control point
  3306. * @param value2 defines the second control point
  3307. * @param value3 defines the third control point
  3308. * @param value4 defines the fourth control point
  3309. * @param amount defines the amount on the spline to use
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3313. var squared = amount * amount;
  3314. var cubed = amount * squared;
  3315. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3316. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3317. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3318. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3319. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3320. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3321. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3322. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3323. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3324. return new Vector3(x, y, z);
  3325. };
  3326. /**
  3327. * 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"
  3328. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3329. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3330. * @param value defines the current value
  3331. * @param min defines the lower range value
  3332. * @param max defines the upper range value
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.Clamp = function (value, min, max) {
  3336. var x = value.x;
  3337. x = (x > max.x) ? max.x : x;
  3338. x = (x < min.x) ? min.x : x;
  3339. var y = value.y;
  3340. y = (y > max.y) ? max.y : y;
  3341. y = (y < min.y) ? min.y : y;
  3342. var z = value.z;
  3343. z = (z > max.z) ? max.z : z;
  3344. z = (z < min.z) ? min.z : z;
  3345. return new Vector3(x, y, z);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3349. * @param value1 defines the first control point
  3350. * @param tangent1 defines the first tangent vector
  3351. * @param value2 defines the second control point
  3352. * @param tangent2 defines the second tangent vector
  3353. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3361. var part3 = (cubed - (2.0 * squared)) + amount;
  3362. var part4 = cubed - squared;
  3363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3365. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3366. return new Vector3(x, y, z);
  3367. };
  3368. /**
  3369. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3370. * @param start defines the start value
  3371. * @param end defines the end value
  3372. * @param amount max defines amount between both (between 0 and 1)
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Lerp = function (start, end, amount) {
  3376. var result = new Vector3(0, 0, 0);
  3377. Vector3.LerpToRef(start, end, amount, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3382. * @param start defines the start value
  3383. * @param end defines the end value
  3384. * @param amount max defines amount between both (between 0 and 1)
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.LerpToRef = function (start, end, amount, result) {
  3388. result.x = start.x + ((end.x - start.x) * amount);
  3389. result.y = start.y + ((end.y - start.y) * amount);
  3390. result.z = start.z + ((end.z - start.z) * amount);
  3391. };
  3392. /**
  3393. * Returns the dot product (float) between the vectors "left" and "right"
  3394. * @param left defines the left operand
  3395. * @param right defines the right operand
  3396. * @returns the dot product
  3397. */
  3398. Vector3.Dot = function (left, right) {
  3399. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3403. * The cross product is then orthogonal to both "left" and "right"
  3404. * @param left defines the left operand
  3405. * @param right defines the right operand
  3406. * @returns the cross product
  3407. */
  3408. Vector3.Cross = function (left, right) {
  3409. var result = Vector3.Zero();
  3410. Vector3.CrossToRef(left, right, result);
  3411. return result;
  3412. };
  3413. /**
  3414. * Sets the passed vector "result" with the cross product of "left" and "right"
  3415. * The cross product is then orthogonal to both "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.CrossToRef = function (left, right, result) {
  3421. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3422. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3423. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3424. result.copyFrom(MathTmp.Vector3[0]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 as the normalization of the passed vector
  3428. * @param vector defines the Vector3 to normalize
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Normalize = function (vector) {
  3432. var result = Vector3.Zero();
  3433. Vector3.NormalizeToRef(vector, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the normalization of the passed first vector
  3438. * @param vector defines the Vector3 to normalize
  3439. * @param result defines the Vector3 where to store the result
  3440. */
  3441. Vector3.NormalizeToRef = function (vector, result) {
  3442. result.copyFrom(vector);
  3443. result.normalize();
  3444. };
  3445. /**
  3446. * Project a Vector3 onto screen space
  3447. * @param vector defines the Vector3 to project
  3448. * @param world defines the world matrix to use
  3449. * @param transform defines the transform (view x projection) matrix to use
  3450. * @param viewport defines the screen viewport to use
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Project = function (vector, world, transform, viewport) {
  3454. var cw = viewport.width;
  3455. var ch = viewport.height;
  3456. var cx = viewport.x;
  3457. var cy = viewport.y;
  3458. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3459. 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);
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(transform, matrix);
  3462. matrix.multiplyToRef(viewportMatrix, matrix);
  3463. return Vector3.TransformCoordinates(vector, matrix);
  3464. };
  3465. /**
  3466. * Unproject from screen space to object space
  3467. * @param source defines the screen space Vector3 to use
  3468. * @param viewportWidth defines the current width of the viewport
  3469. * @param viewportHeight defines the current height of the viewport
  3470. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3475. var matrix = MathTmp.Matrix[0];
  3476. world.multiplyToRef(transform, matrix);
  3477. matrix.invert();
  3478. source.x = source.x / viewportWidth * 2 - 1;
  3479. source.y = -(source.y / viewportHeight * 2 - 1);
  3480. var vector = Vector3.TransformCoordinates(source, matrix);
  3481. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3482. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3483. vector = vector.scale(1.0 / num);
  3484. }
  3485. return vector;
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param view defines the view matrix to use
  3494. * @param projection defines the projection matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3498. var result = Vector3.Zero();
  3499. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Unproject from screen space to object space
  3504. * @param source defines the screen space Vector3 to use
  3505. * @param viewportWidth defines the current width of the viewport
  3506. * @param viewportHeight defines the current height of the viewport
  3507. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3508. * @param view defines the view matrix to use
  3509. * @param projection defines the projection matrix to use
  3510. * @param result defines the Vector3 where to store the result
  3511. */
  3512. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3513. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3514. };
  3515. /**
  3516. * Unproject from screen space to object space
  3517. * @param sourceX defines the screen space x coordinate to use
  3518. * @param sourceY defines the screen space y coordinate to use
  3519. * @param sourceZ defines the screen space z coordinate to use
  3520. * @param viewportWidth defines the current width of the viewport
  3521. * @param viewportHeight defines the current height of the viewport
  3522. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3523. * @param view defines the view matrix to use
  3524. * @param projection defines the projection matrix to use
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3528. var matrix = MathTmp.Matrix[0];
  3529. world.multiplyToRef(view, matrix);
  3530. matrix.multiplyToRef(projection, matrix);
  3531. matrix.invert();
  3532. var screenSource = MathTmp.Vector3[0];
  3533. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3534. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3535. screenSource.z = 2 * sourceZ - 1.0;
  3536. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3537. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3538. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3539. result.scaleInPlace(1.0 / num);
  3540. }
  3541. };
  3542. /**
  3543. * Gets the minimal coordinate values between two Vector3
  3544. * @param left defines the first operand
  3545. * @param right defines the second operand
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Minimize = function (left, right) {
  3549. var min = left.clone();
  3550. min.minimizeInPlace(right);
  3551. return min;
  3552. };
  3553. /**
  3554. * Gets the maximal coordinate values between two Vector3
  3555. * @param left defines the first operand
  3556. * @param right defines the second operand
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Maximize = function (left, right) {
  3560. var max = left.clone();
  3561. max.maximizeInPlace(right);
  3562. return max;
  3563. };
  3564. /**
  3565. * Returns the distance between the vectors "value1" and "value2"
  3566. * @param value1 defines the first operand
  3567. * @param value2 defines the second operand
  3568. * @returns the distance
  3569. */
  3570. Vector3.Distance = function (value1, value2) {
  3571. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3572. };
  3573. /**
  3574. * Returns the squared distance between the vectors "value1" and "value2"
  3575. * @param value1 defines the first operand
  3576. * @param value2 defines the second operand
  3577. * @returns the squared distance
  3578. */
  3579. Vector3.DistanceSquared = function (value1, value2) {
  3580. var x = value1.x - value2.x;
  3581. var y = value1.y - value2.y;
  3582. var z = value1.z - value2.z;
  3583. return (x * x) + (y * y) + (z * z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located at the center between "value1" and "value2"
  3587. * @param value1 defines the first operand
  3588. * @param value2 defines the second operand
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Center = function (value1, value2) {
  3592. var center = value1.add(value2);
  3593. center.scaleInPlace(0.5);
  3594. return center;
  3595. };
  3596. /**
  3597. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3598. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3599. * to something in order to rotate it from its local system to the given target system
  3600. * Note: axis1, axis2 and axis3 are normalized during this operation
  3601. * @param axis1 defines the first axis
  3602. * @param axis2 defines the second axis
  3603. * @param axis3 defines the third axis
  3604. * @returns a new Vector3
  3605. */
  3606. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3607. var rotation = Vector3.Zero();
  3608. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3609. return rotation;
  3610. };
  3611. /**
  3612. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3613. * @param axis1 defines the first axis
  3614. * @param axis2 defines the second axis
  3615. * @param axis3 defines the third axis
  3616. * @param ref defines the Vector3 where to store the result
  3617. */
  3618. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3619. var quat = MathTmp.Quaternion[0];
  3620. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3621. quat.toEulerAnglesToRef(ref);
  3622. };
  3623. return Vector3;
  3624. }());
  3625. BABYLON.Vector3 = Vector3;
  3626. //Vector4 class created for EulerAngle class conversion to Quaternion
  3627. var Vector4 = /** @class */ (function () {
  3628. /**
  3629. * Creates a Vector4 object from the passed floats.
  3630. */
  3631. function Vector4(x, y, z, w) {
  3632. this.x = x;
  3633. this.y = y;
  3634. this.z = z;
  3635. this.w = w;
  3636. }
  3637. /**
  3638. * Returns the string with the Vector4 coordinates.
  3639. */
  3640. Vector4.prototype.toString = function () {
  3641. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3642. };
  3643. /**
  3644. * Returns the string "Vector4".
  3645. */
  3646. Vector4.prototype.getClassName = function () {
  3647. return "Vector4";
  3648. };
  3649. /**
  3650. * Returns the Vector4 hash code.
  3651. */
  3652. Vector4.prototype.getHashCode = function () {
  3653. var hash = this.x || 0;
  3654. hash = (hash * 397) ^ (this.y || 0);
  3655. hash = (hash * 397) ^ (this.z || 0);
  3656. hash = (hash * 397) ^ (this.w || 0);
  3657. return hash;
  3658. };
  3659. // Operators
  3660. /**
  3661. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.asArray = function () {
  3664. var result = new Array();
  3665. this.toArray(result, 0);
  3666. return result;
  3667. };
  3668. /**
  3669. * Populates the passed array from the passed index with the Vector4 coordinates.
  3670. * Returns the Vector4.
  3671. */
  3672. Vector4.prototype.toArray = function (array, index) {
  3673. if (index === undefined) {
  3674. index = 0;
  3675. }
  3676. array[index] = this.x;
  3677. array[index + 1] = this.y;
  3678. array[index + 2] = this.z;
  3679. array[index + 3] = this.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Adds the passed vector to the current Vector4.
  3684. * Returns the updated Vector4.
  3685. */
  3686. Vector4.prototype.addInPlace = function (otherVector) {
  3687. this.x += otherVector.x;
  3688. this.y += otherVector.y;
  3689. this.z += otherVector.z;
  3690. this.w += otherVector.w;
  3691. return this;
  3692. };
  3693. /**
  3694. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3695. */
  3696. Vector4.prototype.add = function (otherVector) {
  3697. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3698. };
  3699. /**
  3700. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3701. * Returns the current Vector4.
  3702. */
  3703. Vector4.prototype.addToRef = function (otherVector, result) {
  3704. result.x = this.x + otherVector.x;
  3705. result.y = this.y + otherVector.y;
  3706. result.z = this.z + otherVector.z;
  3707. result.w = this.w + otherVector.w;
  3708. return this;
  3709. };
  3710. /**
  3711. * Subtract in place the passed vector from the current Vector4.
  3712. * Returns the updated Vector4.
  3713. */
  3714. Vector4.prototype.subtractInPlace = function (otherVector) {
  3715. this.x -= otherVector.x;
  3716. this.y -= otherVector.y;
  3717. this.z -= otherVector.z;
  3718. this.w -= otherVector.w;
  3719. return this;
  3720. };
  3721. /**
  3722. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3723. */
  3724. Vector4.prototype.subtract = function (otherVector) {
  3725. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3726. };
  3727. /**
  3728. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3729. * Returns the current Vector4.
  3730. */
  3731. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3732. result.x = this.x - otherVector.x;
  3733. result.y = this.y - otherVector.y;
  3734. result.z = this.z - otherVector.z;
  3735. result.w = this.w - otherVector.w;
  3736. return this;
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3742. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3743. };
  3744. /**
  3745. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3749. result.x = this.x - x;
  3750. result.y = this.y - y;
  3751. result.z = this.z - z;
  3752. result.w = this.w - w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3757. */
  3758. Vector4.prototype.negate = function () {
  3759. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3760. };
  3761. /**
  3762. * Multiplies the current Vector4 coordinates by scale (float).
  3763. * Returns the updated Vector4.
  3764. */
  3765. Vector4.prototype.scaleInPlace = function (scale) {
  3766. this.x *= scale;
  3767. this.y *= scale;
  3768. this.z *= scale;
  3769. this.w *= scale;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3774. */
  3775. Vector4.prototype.scale = function (scale) {
  3776. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3777. };
  3778. /**
  3779. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3780. * Returns the current Vector4.
  3781. */
  3782. Vector4.prototype.scaleToRef = function (scale, result) {
  3783. result.x = this.x * scale;
  3784. result.y = this.y * scale;
  3785. result.z = this.z * scale;
  3786. result.w = this.w * scale;
  3787. return this;
  3788. };
  3789. /**
  3790. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3791. * @param scale defines the scale factor
  3792. * @param result defines the Vector4 object where to store the result
  3793. * @returns the unmodified current Vector4
  3794. */
  3795. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3796. result.x += this.x * scale;
  3797. result.y += this.y * scale;
  3798. result.z += this.z * scale;
  3799. result.w += this.w * scale;
  3800. return this;
  3801. };
  3802. /**
  3803. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3804. */
  3805. Vector4.prototype.equals = function (otherVector) {
  3806. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3807. };
  3808. /**
  3809. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3810. */
  3811. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3812. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3813. return otherVector
  3814. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3815. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3816. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3817. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3818. };
  3819. /**
  3820. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3821. */
  3822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3823. return this.x === x && this.y === y && this.z === z && this.w === w;
  3824. };
  3825. /**
  3826. * Multiplies in place the current Vector4 by the passed one.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3830. this.x *= otherVector.x;
  3831. this.y *= otherVector.y;
  3832. this.z *= otherVector.z;
  3833. this.w *= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3838. */
  3839. Vector4.prototype.multiply = function (otherVector) {
  3840. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3841. };
  3842. /**
  3843. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3847. result.x = this.x * otherVector.x;
  3848. result.y = this.y * otherVector.y;
  3849. result.z = this.z * otherVector.z;
  3850. result.w = this.w * otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3861. */
  3862. Vector4.prototype.divide = function (otherVector) {
  3863. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3864. };
  3865. /**
  3866. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.divideToRef = function (otherVector, result) {
  3870. result.x = this.x / otherVector.x;
  3871. result.y = this.y / otherVector.y;
  3872. result.z = this.z / otherVector.z;
  3873. result.w = this.w / otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Divides the current Vector3 coordinates by the passed ones.
  3878. * @returns the updated Vector3.
  3879. */
  3880. Vector4.prototype.divideInPlace = function (otherVector) {
  3881. return this.divideToRef(otherVector, this);
  3882. };
  3883. /**
  3884. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3885. * @param other defines the second operand
  3886. * @returns the current updated Vector4
  3887. */
  3888. Vector4.prototype.minimizeInPlace = function (other) {
  3889. if (other.x < this.x)
  3890. this.x = other.x;
  3891. if (other.y < this.y)
  3892. this.y = other.y;
  3893. if (other.z < this.z)
  3894. this.z = other.z;
  3895. if (other.w < this.w)
  3896. this.w = other.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3901. * @param other defines the second operand
  3902. * @returns the current updated Vector4
  3903. */
  3904. Vector4.prototype.maximizeInPlace = function (other) {
  3905. if (other.x > this.x)
  3906. this.x = other.x;
  3907. if (other.y > this.y)
  3908. this.y = other.y;
  3909. if (other.z > this.z)
  3910. this.z = other.z;
  3911. if (other.w > this.w)
  3912. this.w = other.w;
  3913. return this;
  3914. };
  3915. // Properties
  3916. /**
  3917. * Returns the Vector4 length (float).
  3918. */
  3919. Vector4.prototype.length = function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. };
  3922. /**
  3923. * Returns the Vector4 squared length (float).
  3924. */
  3925. Vector4.prototype.lengthSquared = function () {
  3926. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3927. };
  3928. // Methods
  3929. /**
  3930. * Normalizes in place the Vector4.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.normalize = function () {
  3934. var len = this.length();
  3935. if (len === 0)
  3936. return this;
  3937. var num = 1.0 / len;
  3938. this.x *= num;
  3939. this.y *= num;
  3940. this.z *= num;
  3941. this.w *= num;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3946. */
  3947. Vector4.prototype.toVector3 = function () {
  3948. return new Vector3(this.x, this.y, this.z);
  3949. };
  3950. /**
  3951. * Returns a new Vector4 copied from the current one.
  3952. */
  3953. Vector4.prototype.clone = function () {
  3954. return new Vector4(this.x, this.y, this.z, this.w);
  3955. };
  3956. /**
  3957. * Updates the current Vector4 with the passed one coordinates.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.copyFrom = function (source) {
  3961. this.x = source.x;
  3962. this.y = source.y;
  3963. this.z = source.z;
  3964. this.w = source.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Updates the current Vector4 coordinates with the passed floats.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3972. this.x = x;
  3973. this.y = y;
  3974. this.z = z;
  3975. this.w = w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Updates the current Vector4 coordinates with the passed floats.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.set = function (x, y, z, w) {
  3983. return this.copyFromFloats(x, y, z, w);
  3984. };
  3985. // Statics
  3986. /**
  3987. * Returns a new Vector4 set from the starting index of the passed array.
  3988. */
  3989. Vector4.FromArray = function (array, offset) {
  3990. if (!offset) {
  3991. offset = 0;
  3992. }
  3993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3994. };
  3995. /**
  3996. * Updates the passed vector "result" from the starting index of the passed array.
  3997. */
  3998. Vector4.FromArrayToRef = function (array, offset, result) {
  3999. result.x = array[offset];
  4000. result.y = array[offset + 1];
  4001. result.z = array[offset + 2];
  4002. result.w = array[offset + 3];
  4003. };
  4004. /**
  4005. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the passed vector "result" coordinates from the passed floats.
  4012. */
  4013. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4014. result.x = x;
  4015. result.y = y;
  4016. result.z = z;
  4017. result.w = w;
  4018. };
  4019. /**
  4020. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4021. */
  4022. Vector4.Zero = function () {
  4023. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4027. */
  4028. Vector4.One = function () {
  4029. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4030. };
  4031. /**
  4032. * Returns a new normalized Vector4 from the passed one.
  4033. */
  4034. Vector4.Normalize = function (vector) {
  4035. var result = Vector4.Zero();
  4036. Vector4.NormalizeToRef(vector, result);
  4037. return result;
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the normalization of the passed one.
  4041. */
  4042. Vector4.NormalizeToRef = function (vector, result) {
  4043. result.copyFrom(vector);
  4044. result.normalize();
  4045. };
  4046. Vector4.Minimize = function (left, right) {
  4047. var min = left.clone();
  4048. min.minimizeInPlace(right);
  4049. return min;
  4050. };
  4051. Vector4.Maximize = function (left, right) {
  4052. var max = left.clone();
  4053. max.maximizeInPlace(right);
  4054. return max;
  4055. };
  4056. /**
  4057. * Returns the distance (float) between the vectors "value1" and "value2".
  4058. */
  4059. Vector4.Distance = function (value1, value2) {
  4060. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4061. };
  4062. /**
  4063. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4064. */
  4065. Vector4.DistanceSquared = function (value1, value2) {
  4066. var x = value1.x - value2.x;
  4067. var y = value1.y - value2.y;
  4068. var z = value1.z - value2.z;
  4069. var w = value1.w - value2.w;
  4070. return (x * x) + (y * y) + (z * z) + (w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.Center = function (value1, value2) {
  4076. var center = value1.add(value2);
  4077. center.scaleInPlace(0.5);
  4078. return center;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4082. * This methods computes transformed normalized direction vectors only.
  4083. */
  4084. Vector4.TransformNormal = function (vector, transformation) {
  4085. var result = Vector4.Zero();
  4086. Vector4.TransformNormalToRef(vector, transformation, result);
  4087. return result;
  4088. };
  4089. /**
  4090. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4091. * This methods computes transformed normalized direction vectors only.
  4092. */
  4093. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4094. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4095. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4096. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4097. result.x = x;
  4098. result.y = y;
  4099. result.z = z;
  4100. result.w = vector.w;
  4101. };
  4102. /**
  4103. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4107. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4108. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4109. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4110. result.w = w;
  4111. };
  4112. return Vector4;
  4113. }());
  4114. BABYLON.Vector4 = Vector4;
  4115. var Size = /** @class */ (function () {
  4116. /**
  4117. * Creates a Size object from the passed width and height (floats).
  4118. */
  4119. function Size(width, height) {
  4120. this.width = width;
  4121. this.height = height;
  4122. }
  4123. // Returns a string with the Size width and height.
  4124. Size.prototype.toString = function () {
  4125. return "{W: " + this.width + ", H: " + this.height + "}";
  4126. };
  4127. /**
  4128. * Returns the string "Size"
  4129. */
  4130. Size.prototype.getClassName = function () {
  4131. return "Size";
  4132. };
  4133. /**
  4134. * Returns the Size hash code.
  4135. */
  4136. Size.prototype.getHashCode = function () {
  4137. var hash = this.width || 0;
  4138. hash = (hash * 397) ^ (this.height || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Updates the current size from the passed one.
  4143. * Returns the updated Size.
  4144. */
  4145. Size.prototype.copyFrom = function (src) {
  4146. this.width = src.width;
  4147. this.height = src.height;
  4148. };
  4149. /**
  4150. * Updates in place the current Size from the passed floats.
  4151. * Returns the updated Size.
  4152. */
  4153. Size.prototype.copyFromFloats = function (width, height) {
  4154. this.width = width;
  4155. this.height = height;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates in place the current Size from the passed floats.
  4160. * Returns the updated Size.
  4161. */
  4162. Size.prototype.set = function (width, height) {
  4163. return this.copyFromFloats(width, height);
  4164. };
  4165. /**
  4166. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4167. */
  4168. Size.prototype.multiplyByFloats = function (w, h) {
  4169. return new Size(this.width * w, this.height * h);
  4170. };
  4171. /**
  4172. * Returns a new Size copied from the passed one.
  4173. */
  4174. Size.prototype.clone = function () {
  4175. return new Size(this.width, this.height);
  4176. };
  4177. /**
  4178. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4179. */
  4180. Size.prototype.equals = function (other) {
  4181. if (!other) {
  4182. return false;
  4183. }
  4184. return (this.width === other.width) && (this.height === other.height);
  4185. };
  4186. Object.defineProperty(Size.prototype, "surface", {
  4187. /**
  4188. * Returns the surface of the Size : width * height (float).
  4189. */
  4190. get: function () {
  4191. return this.width * this.height;
  4192. },
  4193. enumerable: true,
  4194. configurable: true
  4195. });
  4196. /**
  4197. * Returns a new Size set to (0.0, 0.0)
  4198. */
  4199. Size.Zero = function () {
  4200. return new Size(0.0, 0.0);
  4201. };
  4202. /**
  4203. * Returns a new Size set as the addition result of the current Size and the passed one.
  4204. */
  4205. Size.prototype.add = function (otherSize) {
  4206. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4211. */
  4212. Size.prototype.subtract = function (otherSize) {
  4213. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4214. return r;
  4215. };
  4216. /**
  4217. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4218. */
  4219. Size.Lerp = function (start, end, amount) {
  4220. var w = start.width + ((end.width - start.width) * amount);
  4221. var h = start.height + ((end.height - start.height) * amount);
  4222. return new Size(w, h);
  4223. };
  4224. return Size;
  4225. }());
  4226. BABYLON.Size = Size;
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the passed floats.
  4230. */
  4231. function Quaternion(x, y, z, w) {
  4232. if (x === void 0) { x = 0.0; }
  4233. if (y === void 0) { y = 0.0; }
  4234. if (z === void 0) { z = 0.0; }
  4235. if (w === void 0) { w = 1.0; }
  4236. this.x = x;
  4237. this.y = y;
  4238. this.z = z;
  4239. this.w = w;
  4240. }
  4241. /**
  4242. * Returns a string with the Quaternion coordinates.
  4243. */
  4244. Quaternion.prototype.toString = function () {
  4245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4246. };
  4247. /**
  4248. * Returns the string "Quaternion".
  4249. */
  4250. Quaternion.prototype.getClassName = function () {
  4251. return "Quaternion";
  4252. };
  4253. /**
  4254. * Returns the Quaternion hash code.
  4255. */
  4256. Quaternion.prototype.getHashCode = function () {
  4257. var hash = this.x || 0;
  4258. hash = (hash * 397) ^ (this.y || 0);
  4259. hash = (hash * 397) ^ (this.z || 0);
  4260. hash = (hash * 397) ^ (this.w || 0);
  4261. return hash;
  4262. };
  4263. /**
  4264. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.asArray = function () {
  4267. return [this.x, this.y, this.z, this.w];
  4268. };
  4269. /**
  4270. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4271. */
  4272. Quaternion.prototype.equals = function (otherQuaternion) {
  4273. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4274. };
  4275. /**
  4276. * Returns a new Quaternion copied from the current one.
  4277. */
  4278. Quaternion.prototype.clone = function () {
  4279. return new Quaternion(this.x, this.y, this.z, this.w);
  4280. };
  4281. /**
  4282. * Updates the current Quaternion from the passed one coordinates.
  4283. * Returns the updated Quaterion.
  4284. */
  4285. Quaternion.prototype.copyFrom = function (other) {
  4286. this.x = other.x;
  4287. this.y = other.y;
  4288. this.z = other.z;
  4289. this.w = other.w;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates the current Quaternion from the passed float coordinates.
  4294. * Returns the updated Quaterion.
  4295. */
  4296. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed float coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.set = function (x, y, z, w) {
  4308. return this.copyFromFloats(x, y, z, w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4312. */
  4313. Quaternion.prototype.add = function (other) {
  4314. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4315. };
  4316. /**
  4317. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4318. */
  4319. Quaternion.prototype.subtract = function (other) {
  4320. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4321. };
  4322. /**
  4323. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4324. */
  4325. Quaternion.prototype.scale = function (value) {
  4326. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4327. };
  4328. /**
  4329. * Scale the current Quaternion values by a factor to a given Quaternion
  4330. * @param scale defines the scale factor
  4331. * @param result defines the Quaternion object where to store the result
  4332. * @returns the unmodified current Quaternion
  4333. */
  4334. Quaternion.prototype.scaleToRef = function (scale, result) {
  4335. result.x = this.x * scale;
  4336. result.y = this.y * scale;
  4337. result.z = this.z * scale;
  4338. result.w = this.w * scale;
  4339. return this;
  4340. };
  4341. /**
  4342. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4343. * @param scale defines the scale factor
  4344. * @param result defines the Quaternion object where to store the result
  4345. * @returns the unmodified current Quaternion
  4346. */
  4347. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4348. result.x += this.x * scale;
  4349. result.y += this.y * scale;
  4350. result.z += this.z * scale;
  4351. result.w += this.w * scale;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4356. */
  4357. Quaternion.prototype.multiply = function (q1) {
  4358. var result = new Quaternion(0, 0, 0, 1.0);
  4359. this.multiplyToRef(q1, result);
  4360. return result;
  4361. };
  4362. /**
  4363. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4364. * Returns the current Quaternion.
  4365. */
  4366. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4367. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4368. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4369. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4370. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4371. result.copyFromFloats(x, y, z, w);
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4376. * Returns the updated Quaternion.
  4377. */
  4378. Quaternion.prototype.multiplyInPlace = function (q1) {
  4379. this.multiplyToRef(q1, this);
  4380. return this;
  4381. };
  4382. /**
  4383. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4384. * Returns the current Quaternion.
  4385. */
  4386. Quaternion.prototype.conjugateToRef = function (ref) {
  4387. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4388. return this;
  4389. };
  4390. /**
  4391. * Conjugates in place the current Quaternion.
  4392. * Returns the updated Quaternion.
  4393. */
  4394. Quaternion.prototype.conjugateInPlace = function () {
  4395. this.x *= -1;
  4396. this.y *= -1;
  4397. this.z *= -1;
  4398. return this;
  4399. };
  4400. /**
  4401. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4402. */
  4403. Quaternion.prototype.conjugate = function () {
  4404. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4405. return result;
  4406. };
  4407. /**
  4408. * Returns the Quaternion length (float).
  4409. */
  4410. Quaternion.prototype.length = function () {
  4411. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4412. };
  4413. /**
  4414. * Normalize in place the current Quaternion.
  4415. * Returns the updated Quaternion.
  4416. */
  4417. Quaternion.prototype.normalize = function () {
  4418. var length = 1.0 / this.length();
  4419. this.x *= length;
  4420. this.y *= length;
  4421. this.z *= length;
  4422. this.w *= length;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4427. * @param order is a reserved parameter and is ignore for now
  4428. * @returns the new Vector3
  4429. */
  4430. Quaternion.prototype.toEulerAngles = function (order) {
  4431. if (order === void 0) { order = "YZX"; }
  4432. var result = Vector3.Zero();
  4433. this.toEulerAnglesToRef(result, order);
  4434. return result;
  4435. };
  4436. /**
  4437. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4438. * @param result defines the vector which will be filled with the Euler angles
  4439. * @param order is a reserved parameter and is ignore for now
  4440. * @returns the current Quaternion
  4441. */
  4442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4443. if (order === void 0) { order = "YZX"; }
  4444. var qz = this.z;
  4445. var qx = this.x;
  4446. var qy = this.y;
  4447. var qw = this.w;
  4448. var sqw = qw * qw;
  4449. var sqz = qz * qz;
  4450. var sqx = qx * qx;
  4451. var sqy = qy * qy;
  4452. var zAxisY = qy * qz - qx * qw;
  4453. var limit = .4999999;
  4454. if (zAxisY < -limit) {
  4455. result.y = 2 * Math.atan2(qy, qw);
  4456. result.x = Math.PI / 2;
  4457. result.z = 0;
  4458. }
  4459. else if (zAxisY > limit) {
  4460. result.y = 2 * Math.atan2(qy, qw);
  4461. result.x = -Math.PI / 2;
  4462. result.z = 0;
  4463. }
  4464. else {
  4465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4468. }
  4469. return this;
  4470. };
  4471. /**
  4472. * Updates the passed rotation matrix with the current Quaternion values.
  4473. * Returns the current Quaternion.
  4474. */
  4475. Quaternion.prototype.toRotationMatrix = function (result) {
  4476. var xx = this.x * this.x;
  4477. var yy = this.y * this.y;
  4478. var zz = this.z * this.z;
  4479. var xy = this.x * this.y;
  4480. var zw = this.z * this.w;
  4481. var zx = this.z * this.x;
  4482. var yw = this.y * this.w;
  4483. var yz = this.y * this.z;
  4484. var xw = this.x * this.w;
  4485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4486. result.m[1] = 2.0 * (xy + zw);
  4487. result.m[2] = 2.0 * (zx - yw);
  4488. result.m[3] = 0;
  4489. result.m[4] = 2.0 * (xy - zw);
  4490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4491. result.m[6] = 2.0 * (yz + xw);
  4492. result.m[7] = 0;
  4493. result.m[8] = 2.0 * (zx + yw);
  4494. result.m[9] = 2.0 * (yz - xw);
  4495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4496. result.m[11] = 0;
  4497. result.m[12] = 0;
  4498. result.m[13] = 0;
  4499. result.m[14] = 0;
  4500. result.m[15] = 1.0;
  4501. result._markAsUpdated();
  4502. return this;
  4503. };
  4504. /**
  4505. * Updates the current Quaternion from the passed rotation matrix values.
  4506. * Returns the updated Quaternion.
  4507. */
  4508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4509. Quaternion.FromRotationMatrixToRef(matrix, this);
  4510. return this;
  4511. };
  4512. // Statics
  4513. /**
  4514. * Returns a new Quaternion set from the passed rotation matrix values.
  4515. */
  4516. Quaternion.FromRotationMatrix = function (matrix) {
  4517. var result = new Quaternion();
  4518. Quaternion.FromRotationMatrixToRef(matrix, result);
  4519. return result;
  4520. };
  4521. /**
  4522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4523. */
  4524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4525. var data = matrix.m;
  4526. var m11 = data[0], m12 = data[4], m13 = data[8];
  4527. var m21 = data[1], m22 = data[5], m23 = data[9];
  4528. var m31 = data[2], m32 = data[6], m33 = data[10];
  4529. var trace = m11 + m22 + m33;
  4530. var s;
  4531. if (trace > 0) {
  4532. s = 0.5 / Math.sqrt(trace + 1.0);
  4533. result.w = 0.25 / s;
  4534. result.x = (m32 - m23) * s;
  4535. result.y = (m13 - m31) * s;
  4536. result.z = (m21 - m12) * s;
  4537. }
  4538. else if (m11 > m22 && m11 > m33) {
  4539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4540. result.w = (m32 - m23) / s;
  4541. result.x = 0.25 * s;
  4542. result.y = (m12 + m21) / s;
  4543. result.z = (m13 + m31) / s;
  4544. }
  4545. else if (m22 > m33) {
  4546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4547. result.w = (m13 - m31) / s;
  4548. result.x = (m12 + m21) / s;
  4549. result.y = 0.25 * s;
  4550. result.z = (m23 + m32) / s;
  4551. }
  4552. else {
  4553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4554. result.w = (m21 - m12) / s;
  4555. result.x = (m13 + m31) / s;
  4556. result.y = (m23 + m32) / s;
  4557. result.z = 0.25 * s;
  4558. }
  4559. };
  4560. /**
  4561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4562. */
  4563. Quaternion.Zero = function () {
  4564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4565. };
  4566. /**
  4567. * Returns a new Quaternion as the inverted current Quaternion.
  4568. */
  4569. Quaternion.Inverse = function (q) {
  4570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4571. };
  4572. /**
  4573. * Returns the identity Quaternion.
  4574. */
  4575. Quaternion.Identity = function () {
  4576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4577. };
  4578. Quaternion.IsIdentity = function (quaternion) {
  4579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4580. };
  4581. /**
  4582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4583. */
  4584. Quaternion.RotationAxis = function (axis, angle) {
  4585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4586. };
  4587. /**
  4588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4589. */
  4590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4591. var sin = Math.sin(angle / 2);
  4592. axis.normalize();
  4593. result.w = Math.cos(angle / 2);
  4594. result.x = axis.x * sin;
  4595. result.y = axis.y * sin;
  4596. result.z = axis.z * sin;
  4597. return result;
  4598. };
  4599. /**
  4600. * Retuns a new Quaternion set from the starting index of the passed array.
  4601. */
  4602. Quaternion.FromArray = function (array, offset) {
  4603. if (!offset) {
  4604. offset = 0;
  4605. }
  4606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4610. */
  4611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4612. var q = new Quaternion();
  4613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4614. return q;
  4615. };
  4616. /**
  4617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4618. */
  4619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4621. var halfRoll = roll * 0.5;
  4622. var halfPitch = pitch * 0.5;
  4623. var halfYaw = yaw * 0.5;
  4624. var sinRoll = Math.sin(halfRoll);
  4625. var cosRoll = Math.cos(halfRoll);
  4626. var sinPitch = Math.sin(halfPitch);
  4627. var cosPitch = Math.cos(halfPitch);
  4628. var sinYaw = Math.sin(halfYaw);
  4629. var cosYaw = Math.cos(halfYaw);
  4630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4637. */
  4638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4639. var result = new Quaternion();
  4640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4645. */
  4646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4647. // Produces a quaternion from Euler angles in the z-x-z orientation
  4648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4650. var halfBeta = beta * 0.5;
  4651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4655. };
  4656. /**
  4657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4658. * cf to Vector3.RotationFromAxis() documentation.
  4659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4660. */
  4661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4664. return quat;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4668. * cf to Vector3.RotationFromAxis() documentation.
  4669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4670. */
  4671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4672. var rotMat = MathTmp.Matrix[0];
  4673. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4674. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4675. };
  4676. Quaternion.Slerp = function (left, right, amount) {
  4677. var result = Quaternion.Identity();
  4678. Quaternion.SlerpToRef(left, right, amount, result);
  4679. return result;
  4680. };
  4681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4682. var num2;
  4683. var num3;
  4684. var num = amount;
  4685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4686. var flag = false;
  4687. if (num4 < 0) {
  4688. flag = true;
  4689. num4 = -num4;
  4690. }
  4691. if (num4 > 0.999999) {
  4692. num3 = 1 - num;
  4693. num2 = flag ? -num : num;
  4694. }
  4695. else {
  4696. var num5 = Math.acos(num4);
  4697. var num6 = (1.0 / Math.sin(num5));
  4698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4700. }
  4701. result.x = (num3 * left.x) + (num2 * right.x);
  4702. result.y = (num3 * left.y) + (num2 * right.y);
  4703. result.z = (num3 * left.z) + (num2 * right.z);
  4704. result.w = (num3 * left.w) + (num2 * right.w);
  4705. };
  4706. /**
  4707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4708. */
  4709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4710. var squared = amount * amount;
  4711. var cubed = amount * squared;
  4712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4714. var part3 = (cubed - (2.0 * squared)) + amount;
  4715. var part4 = cubed - squared;
  4716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4720. return new Quaternion(x, y, z, w);
  4721. };
  4722. return Quaternion;
  4723. }());
  4724. BABYLON.Quaternion = Quaternion;
  4725. var Matrix = /** @class */ (function () {
  4726. function Matrix() {
  4727. this._isIdentity = false;
  4728. this._isIdentityDirty = true;
  4729. this.m = new Float32Array(16);
  4730. this._markAsUpdated();
  4731. }
  4732. Matrix.prototype._markAsUpdated = function () {
  4733. this.updateFlag = Matrix._updateFlagSeed++;
  4734. this._isIdentityDirty = true;
  4735. };
  4736. // Properties
  4737. /**
  4738. * Boolean : True is the matrix is the identity matrix
  4739. */
  4740. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4741. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4742. if (this._isIdentityDirty) {
  4743. this._isIdentityDirty = false;
  4744. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4745. this._isIdentity = false;
  4746. }
  4747. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4751. this._isIdentity = false;
  4752. }
  4753. else {
  4754. this._isIdentity = true;
  4755. }
  4756. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4757. this._isIdentity = false;
  4758. }
  4759. }
  4760. return this._isIdentity;
  4761. };
  4762. /**
  4763. * Returns the matrix determinant (float).
  4764. */
  4765. Matrix.prototype.determinant = function () {
  4766. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4767. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4768. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4769. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4770. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4771. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4772. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4773. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4774. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4775. };
  4776. // Methods
  4777. /**
  4778. * Returns the matrix underlying array.
  4779. */
  4780. Matrix.prototype.toArray = function () {
  4781. return this.m;
  4782. };
  4783. /**
  4784. * Returns the matrix underlying array.
  4785. */
  4786. Matrix.prototype.asArray = function () {
  4787. return this.toArray();
  4788. };
  4789. /**
  4790. * Inverts in place the Matrix.
  4791. * Returns the Matrix inverted.
  4792. */
  4793. Matrix.prototype.invert = function () {
  4794. this.invertToRef(this);
  4795. return this;
  4796. };
  4797. /**
  4798. * Sets all the matrix elements to zero.
  4799. * Returns the Matrix.
  4800. */
  4801. Matrix.prototype.reset = function () {
  4802. for (var index = 0; index < 16; index++) {
  4803. this.m[index] = 0.0;
  4804. }
  4805. this._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4810. */
  4811. Matrix.prototype.add = function (other) {
  4812. var result = new Matrix();
  4813. this.addToRef(other, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.addToRef = function (other, result) {
  4821. for (var index = 0; index < 16; index++) {
  4822. result.m[index] = this.m[index] + other.m[index];
  4823. }
  4824. result._markAsUpdated();
  4825. return this;
  4826. };
  4827. /**
  4828. * Adds in place the passed matrix to the current Matrix.
  4829. * Returns the updated Matrix.
  4830. */
  4831. Matrix.prototype.addToSelf = function (other) {
  4832. for (var index = 0; index < 16; index++) {
  4833. this.m[index] += other.m[index];
  4834. }
  4835. this._markAsUpdated();
  4836. return this;
  4837. };
  4838. /**
  4839. * Sets the passed matrix with the current inverted Matrix.
  4840. * Returns the unmodified current Matrix.
  4841. */
  4842. Matrix.prototype.invertToRef = function (other) {
  4843. var l1 = this.m[0];
  4844. var l2 = this.m[1];
  4845. var l3 = this.m[2];
  4846. var l4 = this.m[3];
  4847. var l5 = this.m[4];
  4848. var l6 = this.m[5];
  4849. var l7 = this.m[6];
  4850. var l8 = this.m[7];
  4851. var l9 = this.m[8];
  4852. var l10 = this.m[9];
  4853. var l11 = this.m[10];
  4854. var l12 = this.m[11];
  4855. var l13 = this.m[12];
  4856. var l14 = this.m[13];
  4857. var l15 = this.m[14];
  4858. var l16 = this.m[15];
  4859. var l17 = (l11 * l16) - (l12 * l15);
  4860. var l18 = (l10 * l16) - (l12 * l14);
  4861. var l19 = (l10 * l15) - (l11 * l14);
  4862. var l20 = (l9 * l16) - (l12 * l13);
  4863. var l21 = (l9 * l15) - (l11 * l13);
  4864. var l22 = (l9 * l14) - (l10 * l13);
  4865. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4866. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4867. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4868. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4869. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4870. var l28 = (l7 * l16) - (l8 * l15);
  4871. var l29 = (l6 * l16) - (l8 * l14);
  4872. var l30 = (l6 * l15) - (l7 * l14);
  4873. var l31 = (l5 * l16) - (l8 * l13);
  4874. var l32 = (l5 * l15) - (l7 * l13);
  4875. var l33 = (l5 * l14) - (l6 * l13);
  4876. var l34 = (l7 * l12) - (l8 * l11);
  4877. var l35 = (l6 * l12) - (l8 * l10);
  4878. var l36 = (l6 * l11) - (l7 * l10);
  4879. var l37 = (l5 * l12) - (l8 * l9);
  4880. var l38 = (l5 * l11) - (l7 * l9);
  4881. var l39 = (l5 * l10) - (l6 * l9);
  4882. other.m[0] = l23 * l27;
  4883. other.m[4] = l24 * l27;
  4884. other.m[8] = l25 * l27;
  4885. other.m[12] = l26 * l27;
  4886. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4887. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4888. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4889. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4890. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4891. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4892. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4893. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4894. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4895. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4896. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4897. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4898. other._markAsUpdated();
  4899. return this;
  4900. };
  4901. /**
  4902. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4903. * Returns the updated Matrix.
  4904. */
  4905. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4906. this.m[12] = x;
  4907. this.m[13] = y;
  4908. this.m[14] = z;
  4909. this._markAsUpdated();
  4910. return this;
  4911. };
  4912. /**
  4913. * Inserts the translation vector in the current Matrix.
  4914. * Returns the updated Matrix.
  4915. */
  4916. Matrix.prototype.setTranslation = function (vector3) {
  4917. this.m[12] = vector3.x;
  4918. this.m[13] = vector3.y;
  4919. this.m[14] = vector3.z;
  4920. this._markAsUpdated();
  4921. return this;
  4922. };
  4923. /**
  4924. * Returns a new Vector3 as the extracted translation from the Matrix.
  4925. */
  4926. Matrix.prototype.getTranslation = function () {
  4927. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4928. };
  4929. /**
  4930. * Fill a Vector3 with the extracted translation from the Matrix.
  4931. */
  4932. Matrix.prototype.getTranslationToRef = function (result) {
  4933. result.x = this.m[12];
  4934. result.y = this.m[13];
  4935. result.z = this.m[14];
  4936. return this;
  4937. };
  4938. /**
  4939. * Remove rotation and scaling part from the Matrix.
  4940. * Returns the updated Matrix.
  4941. */
  4942. Matrix.prototype.removeRotationAndScaling = function () {
  4943. this.setRowFromFloats(0, 1, 0, 0, 0);
  4944. this.setRowFromFloats(1, 0, 1, 0, 0);
  4945. this.setRowFromFloats(2, 0, 0, 1, 0);
  4946. return this;
  4947. };
  4948. /**
  4949. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4950. */
  4951. Matrix.prototype.multiply = function (other) {
  4952. var result = new Matrix();
  4953. this.multiplyToRef(other, result);
  4954. return result;
  4955. };
  4956. /**
  4957. * Updates the current Matrix from the passed one values.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.copyFrom = function (other) {
  4961. for (var index = 0; index < 16; index++) {
  4962. this.m[index] = other.m[index];
  4963. }
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Populates the passed array from the starting index with the Matrix values.
  4969. * Returns the Matrix.
  4970. */
  4971. Matrix.prototype.copyToArray = function (array, offset) {
  4972. if (offset === void 0) { offset = 0; }
  4973. for (var index = 0; index < 16; index++) {
  4974. array[offset + index] = this.m[index];
  4975. }
  4976. return this;
  4977. };
  4978. /**
  4979. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4980. */
  4981. Matrix.prototype.multiplyToRef = function (other, result) {
  4982. this.multiplyToArray(other, result.m, 0);
  4983. result._markAsUpdated();
  4984. return this;
  4985. };
  4986. /**
  4987. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4988. */
  4989. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4990. var tm0 = this.m[0];
  4991. var tm1 = this.m[1];
  4992. var tm2 = this.m[2];
  4993. var tm3 = this.m[3];
  4994. var tm4 = this.m[4];
  4995. var tm5 = this.m[5];
  4996. var tm6 = this.m[6];
  4997. var tm7 = this.m[7];
  4998. var tm8 = this.m[8];
  4999. var tm9 = this.m[9];
  5000. var tm10 = this.m[10];
  5001. var tm11 = this.m[11];
  5002. var tm12 = this.m[12];
  5003. var tm13 = this.m[13];
  5004. var tm14 = this.m[14];
  5005. var tm15 = this.m[15];
  5006. var om0 = other.m[0];
  5007. var om1 = other.m[1];
  5008. var om2 = other.m[2];
  5009. var om3 = other.m[3];
  5010. var om4 = other.m[4];
  5011. var om5 = other.m[5];
  5012. var om6 = other.m[6];
  5013. var om7 = other.m[7];
  5014. var om8 = other.m[8];
  5015. var om9 = other.m[9];
  5016. var om10 = other.m[10];
  5017. var om11 = other.m[11];
  5018. var om12 = other.m[12];
  5019. var om13 = other.m[13];
  5020. var om14 = other.m[14];
  5021. var om15 = other.m[15];
  5022. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5023. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5024. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5025. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5026. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5027. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5028. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5029. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5030. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5031. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5032. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5033. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5034. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5035. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5036. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5037. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5038. return this;
  5039. };
  5040. /**
  5041. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5042. */
  5043. Matrix.prototype.equals = function (value) {
  5044. return value &&
  5045. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5046. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5047. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5048. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5049. };
  5050. /**
  5051. * Returns a new Matrix from the current Matrix.
  5052. */
  5053. Matrix.prototype.clone = function () {
  5054. 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]);
  5055. };
  5056. /**
  5057. * Returns the string "Matrix"
  5058. */
  5059. Matrix.prototype.getClassName = function () {
  5060. return "Matrix";
  5061. };
  5062. /**
  5063. * Returns the Matrix hash code.
  5064. */
  5065. Matrix.prototype.getHashCode = function () {
  5066. var hash = this.m[0] || 0;
  5067. for (var i = 1; i < 16; i++) {
  5068. hash = (hash * 397) ^ (this.m[i] || 0);
  5069. }
  5070. return hash;
  5071. };
  5072. /**
  5073. * Decomposes the current Matrix into :
  5074. * - a scale vector3 passed as a reference to update,
  5075. * - a rotation quaternion passed as a reference to update,
  5076. * - a translation vector3 passed as a reference to update.
  5077. * Returns the true if operation was successful.
  5078. */
  5079. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5080. translation.x = this.m[12];
  5081. translation.y = this.m[13];
  5082. translation.z = this.m[14];
  5083. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5084. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5085. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5086. if (this.determinant() <= 0) {
  5087. scale.y *= -1;
  5088. }
  5089. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5090. rotation.x = 0;
  5091. rotation.y = 0;
  5092. rotation.z = 0;
  5093. rotation.w = 1;
  5094. return false;
  5095. }
  5096. 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]);
  5097. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5098. return true;
  5099. };
  5100. /**
  5101. * Returns the index-th row of the current matrix as a new Vector4.
  5102. */
  5103. Matrix.prototype.getRow = function (index) {
  5104. if (index < 0 || index > 3) {
  5105. return null;
  5106. }
  5107. var i = index * 4;
  5108. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5109. };
  5110. /**
  5111. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5112. * Returns the updated Matrix.
  5113. */
  5114. Matrix.prototype.setRow = function (index, row) {
  5115. if (index < 0 || index > 3) {
  5116. return this;
  5117. }
  5118. var i = index * 4;
  5119. this.m[i + 0] = row.x;
  5120. this.m[i + 1] = row.y;
  5121. this.m[i + 2] = row.z;
  5122. this.m[i + 3] = row.w;
  5123. this._markAsUpdated();
  5124. return this;
  5125. };
  5126. /**
  5127. * Compute the transpose of the matrix.
  5128. * Returns a new Matrix.
  5129. */
  5130. Matrix.prototype.transpose = function () {
  5131. return Matrix.Transpose(this);
  5132. };
  5133. /**
  5134. * Compute the transpose of the matrix.
  5135. * Returns the current matrix.
  5136. */
  5137. Matrix.prototype.transposeToRef = function (result) {
  5138. Matrix.TransposeToRef(this, result);
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5143. * Returns the updated Matrix.
  5144. */
  5145. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5146. if (index < 0 || index > 3) {
  5147. return this;
  5148. }
  5149. var i = index * 4;
  5150. this.m[i + 0] = x;
  5151. this.m[i + 1] = y;
  5152. this.m[i + 2] = z;
  5153. this.m[i + 3] = w;
  5154. this._markAsUpdated();
  5155. return this;
  5156. };
  5157. /**
  5158. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5159. * @param scale defines the scale factor
  5160. * @returns a new Matrix
  5161. */
  5162. Matrix.prototype.scale = function (scale) {
  5163. var result = new Matrix();
  5164. this.scaleToRef(scale, result);
  5165. return result;
  5166. };
  5167. /**
  5168. * Scale the current Matrix values by a factor to a given result Matrix
  5169. * @param scale defines the scale factor
  5170. * @param result defines the Matrix to store the result
  5171. * @returns the current Matrix
  5172. */
  5173. Matrix.prototype.scaleToRef = function (scale, result) {
  5174. for (var index = 0; index < 16; index++) {
  5175. result.m[index] = this.m[index] * scale;
  5176. }
  5177. result._markAsUpdated();
  5178. return this;
  5179. };
  5180. /**
  5181. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5182. * @param scale defines the scale factor
  5183. * @param result defines the Matrix to store the result
  5184. * @returns the current Matrix
  5185. */
  5186. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5187. for (var index = 0; index < 16; index++) {
  5188. result.m[index] += this.m[index] * scale;
  5189. }
  5190. result._markAsUpdated();
  5191. return this;
  5192. };
  5193. /**
  5194. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5195. * @param ref matrix to store the result
  5196. */
  5197. Matrix.prototype.toNormalMatrix = function (ref) {
  5198. this.invertToRef(ref);
  5199. ref.transpose();
  5200. var m = ref.m;
  5201. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5202. };
  5203. /**
  5204. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5205. */
  5206. Matrix.prototype.getRotationMatrix = function () {
  5207. var result = Matrix.Identity();
  5208. this.getRotationMatrixToRef(result);
  5209. return result;
  5210. };
  5211. /**
  5212. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5213. * Returns the current Matrix.
  5214. */
  5215. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5216. var m = this.m;
  5217. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5218. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5219. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5220. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5221. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5222. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5223. 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);
  5224. return this;
  5225. };
  5226. // Statics
  5227. /**
  5228. * Returns a new Matrix set from the starting index of the passed array.
  5229. */
  5230. Matrix.FromArray = function (array, offset) {
  5231. var result = new Matrix();
  5232. if (!offset) {
  5233. offset = 0;
  5234. }
  5235. Matrix.FromArrayToRef(array, offset, result);
  5236. return result;
  5237. };
  5238. /**
  5239. * Sets the passed "result" matrix from the starting index of the passed array.
  5240. */
  5241. Matrix.FromArrayToRef = function (array, offset, result) {
  5242. for (var index = 0; index < 16; index++) {
  5243. result.m[index] = array[index + offset];
  5244. }
  5245. result._markAsUpdated();
  5246. };
  5247. /**
  5248. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5249. */
  5250. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5251. for (var index = 0; index < 16; index++) {
  5252. result.m[index] = array[index + offset] * scale;
  5253. }
  5254. result._markAsUpdated();
  5255. };
  5256. /**
  5257. * Sets the passed matrix "result" with the 16 passed floats.
  5258. */
  5259. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5260. result.m[0] = initialM11;
  5261. result.m[1] = initialM12;
  5262. result.m[2] = initialM13;
  5263. result.m[3] = initialM14;
  5264. result.m[4] = initialM21;
  5265. result.m[5] = initialM22;
  5266. result.m[6] = initialM23;
  5267. result.m[7] = initialM24;
  5268. result.m[8] = initialM31;
  5269. result.m[9] = initialM32;
  5270. result.m[10] = initialM33;
  5271. result.m[11] = initialM34;
  5272. result.m[12] = initialM41;
  5273. result.m[13] = initialM42;
  5274. result.m[14] = initialM43;
  5275. result.m[15] = initialM44;
  5276. result._markAsUpdated();
  5277. };
  5278. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5279. /**
  5280. * Static identity matrix to be used as readonly matrix
  5281. * Must not be updated.
  5282. */
  5283. get: function () {
  5284. return Matrix._identityReadOnly;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. /**
  5290. * Returns a new Matrix set from the 16 passed floats.
  5291. */
  5292. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5293. var result = new Matrix();
  5294. result.m[0] = initialM11;
  5295. result.m[1] = initialM12;
  5296. result.m[2] = initialM13;
  5297. result.m[3] = initialM14;
  5298. result.m[4] = initialM21;
  5299. result.m[5] = initialM22;
  5300. result.m[6] = initialM23;
  5301. result.m[7] = initialM24;
  5302. result.m[8] = initialM31;
  5303. result.m[9] = initialM32;
  5304. result.m[10] = initialM33;
  5305. result.m[11] = initialM34;
  5306. result.m[12] = initialM41;
  5307. result.m[13] = initialM42;
  5308. result.m[14] = initialM43;
  5309. result.m[15] = initialM44;
  5310. return result;
  5311. };
  5312. /**
  5313. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5314. */
  5315. Matrix.Compose = function (scale, rotation, translation) {
  5316. var result = Matrix.Identity();
  5317. Matrix.ComposeToRef(scale, rotation, translation, result);
  5318. return result;
  5319. };
  5320. /**
  5321. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5322. */
  5323. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5324. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5325. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5326. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5327. result.setTranslation(translation);
  5328. };
  5329. /**
  5330. * Returns a new indentity Matrix.
  5331. */
  5332. Matrix.Identity = function () {
  5333. 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);
  5334. };
  5335. /**
  5336. * Sets the passed "result" as an identity matrix.
  5337. */
  5338. Matrix.IdentityToRef = function (result) {
  5339. 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);
  5340. };
  5341. /**
  5342. * Returns a new zero Matrix.
  5343. */
  5344. Matrix.Zero = function () {
  5345. 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);
  5346. };
  5347. /**
  5348. * Returns a new rotation matrix for "angle" radians around the X axis.
  5349. */
  5350. Matrix.RotationX = function (angle) {
  5351. var result = new Matrix();
  5352. Matrix.RotationXToRef(angle, result);
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix as the passed inverted one.
  5357. */
  5358. Matrix.Invert = function (source) {
  5359. var result = new Matrix();
  5360. source.invertToRef(result);
  5361. return result;
  5362. };
  5363. /**
  5364. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5365. */
  5366. Matrix.RotationXToRef = function (angle, result) {
  5367. var s = Math.sin(angle);
  5368. var c = Math.cos(angle);
  5369. result.m[0] = 1.0;
  5370. result.m[15] = 1.0;
  5371. result.m[5] = c;
  5372. result.m[10] = c;
  5373. result.m[9] = -s;
  5374. result.m[6] = s;
  5375. result.m[1] = 0.0;
  5376. result.m[2] = 0.0;
  5377. result.m[3] = 0.0;
  5378. result.m[4] = 0.0;
  5379. result.m[7] = 0.0;
  5380. result.m[8] = 0.0;
  5381. result.m[11] = 0.0;
  5382. result.m[12] = 0.0;
  5383. result.m[13] = 0.0;
  5384. result.m[14] = 0.0;
  5385. result._markAsUpdated();
  5386. };
  5387. /**
  5388. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5389. */
  5390. Matrix.RotationY = function (angle) {
  5391. var result = new Matrix();
  5392. Matrix.RotationYToRef(angle, result);
  5393. return result;
  5394. };
  5395. /**
  5396. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5397. */
  5398. Matrix.RotationYToRef = function (angle, result) {
  5399. var s = Math.sin(angle);
  5400. var c = Math.cos(angle);
  5401. result.m[5] = 1.0;
  5402. result.m[15] = 1.0;
  5403. result.m[0] = c;
  5404. result.m[2] = -s;
  5405. result.m[8] = s;
  5406. result.m[10] = c;
  5407. result.m[1] = 0.0;
  5408. result.m[3] = 0.0;
  5409. result.m[4] = 0.0;
  5410. result.m[6] = 0.0;
  5411. result.m[7] = 0.0;
  5412. result.m[9] = 0.0;
  5413. result.m[11] = 0.0;
  5414. result.m[12] = 0.0;
  5415. result.m[13] = 0.0;
  5416. result.m[14] = 0.0;
  5417. result._markAsUpdated();
  5418. };
  5419. /**
  5420. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5421. */
  5422. Matrix.RotationZ = function (angle) {
  5423. var result = new Matrix();
  5424. Matrix.RotationZToRef(angle, result);
  5425. return result;
  5426. };
  5427. /**
  5428. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5429. */
  5430. Matrix.RotationZToRef = function (angle, result) {
  5431. var s = Math.sin(angle);
  5432. var c = Math.cos(angle);
  5433. result.m[10] = 1.0;
  5434. result.m[15] = 1.0;
  5435. result.m[0] = c;
  5436. result.m[1] = s;
  5437. result.m[4] = -s;
  5438. result.m[5] = c;
  5439. result.m[2] = 0.0;
  5440. result.m[3] = 0.0;
  5441. result.m[6] = 0.0;
  5442. result.m[7] = 0.0;
  5443. result.m[8] = 0.0;
  5444. result.m[9] = 0.0;
  5445. result.m[11] = 0.0;
  5446. result.m[12] = 0.0;
  5447. result.m[13] = 0.0;
  5448. result.m[14] = 0.0;
  5449. result._markAsUpdated();
  5450. };
  5451. /**
  5452. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5453. */
  5454. Matrix.RotationAxis = function (axis, angle) {
  5455. var result = Matrix.Zero();
  5456. Matrix.RotationAxisToRef(axis, angle, result);
  5457. return result;
  5458. };
  5459. /**
  5460. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5461. */
  5462. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5463. var s = Math.sin(-angle);
  5464. var c = Math.cos(-angle);
  5465. var c1 = 1 - c;
  5466. axis.normalize();
  5467. result.m[0] = (axis.x * axis.x) * c1 + c;
  5468. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5469. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5470. result.m[3] = 0.0;
  5471. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5472. result.m[5] = (axis.y * axis.y) * c1 + c;
  5473. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5474. result.m[7] = 0.0;
  5475. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5476. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5477. result.m[10] = (axis.z * axis.z) * c1 + c;
  5478. result.m[11] = 0.0;
  5479. result.m[15] = 1.0;
  5480. result._markAsUpdated();
  5481. };
  5482. /**
  5483. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5484. */
  5485. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5486. var result = new Matrix();
  5487. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5492. */
  5493. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5494. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5495. this._tempQuaternion.toRotationMatrix(result);
  5496. };
  5497. /**
  5498. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5499. */
  5500. Matrix.Scaling = function (x, y, z) {
  5501. var result = Matrix.Zero();
  5502. Matrix.ScalingToRef(x, y, z, result);
  5503. return result;
  5504. };
  5505. /**
  5506. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5507. */
  5508. Matrix.ScalingToRef = function (x, y, z, result) {
  5509. result.m[0] = x;
  5510. result.m[1] = 0.0;
  5511. result.m[2] = 0.0;
  5512. result.m[3] = 0.0;
  5513. result.m[4] = 0.0;
  5514. result.m[5] = y;
  5515. result.m[6] = 0.0;
  5516. result.m[7] = 0.0;
  5517. result.m[8] = 0.0;
  5518. result.m[9] = 0.0;
  5519. result.m[10] = z;
  5520. result.m[11] = 0.0;
  5521. result.m[12] = 0.0;
  5522. result.m[13] = 0.0;
  5523. result.m[14] = 0.0;
  5524. result.m[15] = 1.0;
  5525. result._markAsUpdated();
  5526. };
  5527. /**
  5528. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5529. */
  5530. Matrix.Translation = function (x, y, z) {
  5531. var result = Matrix.Identity();
  5532. Matrix.TranslationToRef(x, y, z, result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5537. */
  5538. Matrix.TranslationToRef = function (x, y, z, result) {
  5539. 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);
  5540. };
  5541. /**
  5542. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5543. * @param startValue defines the start value
  5544. * @param endValue defines the end value
  5545. * @param gradient defines the gradient factor
  5546. * @returns the new matrix
  5547. */
  5548. Matrix.Lerp = function (startValue, endValue, gradient) {
  5549. var result = Matrix.Zero();
  5550. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5551. return result;
  5552. };
  5553. /**
  5554. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5555. * @param startValue defines the start value
  5556. * @param endValue defines the end value
  5557. * @param gradient defines the gradient factor
  5558. * @param result defines the Matrix object where to store data
  5559. */
  5560. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5561. for (var index = 0; index < 16; index++) {
  5562. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5563. }
  5564. result._markAsUpdated();
  5565. };
  5566. /**
  5567. * Returns a new Matrix whose values are computed by :
  5568. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5569. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5570. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5571. */
  5572. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5573. var startScale = new Vector3(0, 0, 0);
  5574. var startRotation = new Quaternion();
  5575. var startTranslation = new Vector3(0, 0, 0);
  5576. startValue.decompose(startScale, startRotation, startTranslation);
  5577. var endScale = new Vector3(0, 0, 0);
  5578. var endRotation = new Quaternion();
  5579. var endTranslation = new Vector3(0, 0, 0);
  5580. endValue.decompose(endScale, endRotation, endTranslation);
  5581. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5582. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5583. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5584. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5585. };
  5586. /**
  5587. * 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".
  5588. * This methods works for a Left-Handed system.
  5589. */
  5590. Matrix.LookAtLH = function (eye, target, up) {
  5591. var result = Matrix.Zero();
  5592. Matrix.LookAtLHToRef(eye, target, up, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * 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".
  5597. * This methods works for a Left-Handed system.
  5598. */
  5599. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5600. // Z axis
  5601. target.subtractToRef(eye, this._zAxis);
  5602. this._zAxis.normalize();
  5603. // X axis
  5604. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5605. if (this._xAxis.lengthSquared() === 0) {
  5606. this._xAxis.x = 1.0;
  5607. }
  5608. else {
  5609. this._xAxis.normalize();
  5610. }
  5611. // Y axis
  5612. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5613. this._yAxis.normalize();
  5614. // Eye angles
  5615. var ex = -Vector3.Dot(this._xAxis, eye);
  5616. var ey = -Vector3.Dot(this._yAxis, eye);
  5617. var ez = -Vector3.Dot(this._zAxis, eye);
  5618. 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);
  5619. };
  5620. /**
  5621. * 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".
  5622. * This methods works for a Right-Handed system.
  5623. */
  5624. Matrix.LookAtRH = function (eye, target, up) {
  5625. var result = Matrix.Zero();
  5626. Matrix.LookAtRHToRef(eye, target, up, result);
  5627. return result;
  5628. };
  5629. /**
  5630. * 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".
  5631. * This methods works for a Left-Handed system.
  5632. */
  5633. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5634. // Z axis
  5635. eye.subtractToRef(target, this._zAxis);
  5636. this._zAxis.normalize();
  5637. // X axis
  5638. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5639. if (this._xAxis.lengthSquared() === 0) {
  5640. this._xAxis.x = 1.0;
  5641. }
  5642. else {
  5643. this._xAxis.normalize();
  5644. }
  5645. // Y axis
  5646. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5647. this._yAxis.normalize();
  5648. // Eye angles
  5649. var ex = -Vector3.Dot(this._xAxis, eye);
  5650. var ey = -Vector3.Dot(this._yAxis, eye);
  5651. var ez = -Vector3.Dot(this._zAxis, eye);
  5652. 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);
  5653. };
  5654. /**
  5655. * 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.
  5656. */
  5657. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * 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.
  5664. */
  5665. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5666. var n = znear;
  5667. var f = zfar;
  5668. var a = 2.0 / width;
  5669. var b = 2.0 / height;
  5670. var c = 2.0 / (f - n);
  5671. var d = -(f + n) / (f - n);
  5672. 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);
  5673. };
  5674. /**
  5675. * 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.
  5676. */
  5677. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5678. var matrix = Matrix.Zero();
  5679. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5680. return matrix;
  5681. };
  5682. /**
  5683. * 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.
  5684. */
  5685. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5686. var n = znear;
  5687. var f = zfar;
  5688. var a = 2.0 / (right - left);
  5689. var b = 2.0 / (top - bottom);
  5690. var c = 2.0 / (f - n);
  5691. var d = -(f + n) / (f - n);
  5692. var i0 = (left + right) / (left - right);
  5693. var i1 = (top + bottom) / (bottom - top);
  5694. 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);
  5695. };
  5696. /**
  5697. * 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.
  5698. */
  5699. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5700. var matrix = Matrix.Zero();
  5701. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5702. return matrix;
  5703. };
  5704. /**
  5705. * 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.
  5706. */
  5707. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5708. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5709. result.m[10] *= -1.0;
  5710. };
  5711. /**
  5712. * 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.
  5713. */
  5714. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5715. var matrix = Matrix.Zero();
  5716. var n = znear;
  5717. var f = zfar;
  5718. var a = 2.0 * n / width;
  5719. var b = 2.0 * n / height;
  5720. var c = (f + n) / (f - n);
  5721. var d = -2.0 * f * n / (f - n);
  5722. 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);
  5723. return matrix;
  5724. };
  5725. /**
  5726. * 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.
  5727. */
  5728. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5729. var matrix = Matrix.Zero();
  5730. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5731. return matrix;
  5732. };
  5733. /**
  5734. * 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.
  5735. */
  5736. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5737. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5738. var n = znear;
  5739. var f = zfar;
  5740. var t = 1.0 / (Math.tan(fov * 0.5));
  5741. var a = isVerticalFovFixed ? (t / aspect) : t;
  5742. var b = isVerticalFovFixed ? t : (t * aspect);
  5743. var c = (f + n) / (f - n);
  5744. var d = -2.0 * f * n / (f - n);
  5745. 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);
  5746. };
  5747. /**
  5748. * 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.
  5749. */
  5750. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5751. var matrix = Matrix.Zero();
  5752. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5753. return matrix;
  5754. };
  5755. /**
  5756. * 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.
  5757. */
  5758. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5759. //alternatively this could be expressed as:
  5760. // m = PerspectiveFovLHToRef
  5761. // m[10] *= -1.0;
  5762. // m[11] *= -1.0;
  5763. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5764. var n = znear;
  5765. var f = zfar;
  5766. var t = 1.0 / (Math.tan(fov * 0.5));
  5767. var a = isVerticalFovFixed ? (t / aspect) : t;
  5768. var b = isVerticalFovFixed ? t : (t * aspect);
  5769. var c = -(f + n) / (f - n);
  5770. var d = -2 * f * n / (f - n);
  5771. 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);
  5772. };
  5773. /**
  5774. * 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.
  5775. */
  5776. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5777. if (rightHanded === void 0) { rightHanded = false; }
  5778. var rightHandedFactor = rightHanded ? -1 : 1;
  5779. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5780. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5781. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5782. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5783. var xScale = 2.0 / (leftTan + rightTan);
  5784. var yScale = 2.0 / (upTan + downTan);
  5785. result.m[0] = xScale;
  5786. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5787. result.m[5] = yScale;
  5788. result.m[6] = result.m[7] = 0.0;
  5789. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5790. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5791. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5792. result.m[10] = -zfar / (znear - zfar);
  5793. result.m[11] = 1.0 * rightHandedFactor;
  5794. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5795. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5796. // result.m[14] = (znear * zfar) / (znear - zfar);
  5797. result._markAsUpdated();
  5798. };
  5799. /**
  5800. * Returns the final transformation matrix : world * view * projection * viewport
  5801. */
  5802. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5803. var cw = viewport.width;
  5804. var ch = viewport.height;
  5805. var cx = viewport.x;
  5806. var cy = viewport.y;
  5807. 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);
  5808. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5809. };
  5810. /**
  5811. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5812. */
  5813. Matrix.GetAsMatrix2x2 = function (matrix) {
  5814. return new Float32Array([
  5815. matrix.m[0], matrix.m[1],
  5816. matrix.m[4], matrix.m[5]
  5817. ]);
  5818. };
  5819. /**
  5820. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5821. */
  5822. Matrix.GetAsMatrix3x3 = function (matrix) {
  5823. return new Float32Array([
  5824. matrix.m[0], matrix.m[1], matrix.m[2],
  5825. matrix.m[4], matrix.m[5], matrix.m[6],
  5826. matrix.m[8], matrix.m[9], matrix.m[10]
  5827. ]);
  5828. };
  5829. /**
  5830. * Compute the transpose of the passed Matrix.
  5831. * Returns a new Matrix.
  5832. */
  5833. Matrix.Transpose = function (matrix) {
  5834. var result = new Matrix();
  5835. Matrix.TransposeToRef(matrix, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5840. */
  5841. Matrix.TransposeToRef = function (matrix, result) {
  5842. result.m[0] = matrix.m[0];
  5843. result.m[1] = matrix.m[4];
  5844. result.m[2] = matrix.m[8];
  5845. result.m[3] = matrix.m[12];
  5846. result.m[4] = matrix.m[1];
  5847. result.m[5] = matrix.m[5];
  5848. result.m[6] = matrix.m[9];
  5849. result.m[7] = matrix.m[13];
  5850. result.m[8] = matrix.m[2];
  5851. result.m[9] = matrix.m[6];
  5852. result.m[10] = matrix.m[10];
  5853. result.m[11] = matrix.m[14];
  5854. result.m[12] = matrix.m[3];
  5855. result.m[13] = matrix.m[7];
  5856. result.m[14] = matrix.m[11];
  5857. result.m[15] = matrix.m[15];
  5858. };
  5859. /**
  5860. * Returns a new Matrix as the reflection matrix across the passed plane.
  5861. */
  5862. Matrix.Reflection = function (plane) {
  5863. var matrix = new Matrix();
  5864. Matrix.ReflectionToRef(plane, matrix);
  5865. return matrix;
  5866. };
  5867. /**
  5868. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5869. */
  5870. Matrix.ReflectionToRef = function (plane, result) {
  5871. plane.normalize();
  5872. var x = plane.normal.x;
  5873. var y = plane.normal.y;
  5874. var z = plane.normal.z;
  5875. var temp = -2 * x;
  5876. var temp2 = -2 * y;
  5877. var temp3 = -2 * z;
  5878. result.m[0] = (temp * x) + 1;
  5879. result.m[1] = temp2 * x;
  5880. result.m[2] = temp3 * x;
  5881. result.m[3] = 0.0;
  5882. result.m[4] = temp * y;
  5883. result.m[5] = (temp2 * y) + 1;
  5884. result.m[6] = temp3 * y;
  5885. result.m[7] = 0.0;
  5886. result.m[8] = temp * z;
  5887. result.m[9] = temp2 * z;
  5888. result.m[10] = (temp3 * z) + 1;
  5889. result.m[11] = 0.0;
  5890. result.m[12] = temp * plane.d;
  5891. result.m[13] = temp2 * plane.d;
  5892. result.m[14] = temp3 * plane.d;
  5893. result.m[15] = 1.0;
  5894. result._markAsUpdated();
  5895. };
  5896. /**
  5897. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5898. */
  5899. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5900. result.m[0] = xaxis.x;
  5901. result.m[1] = xaxis.y;
  5902. result.m[2] = xaxis.z;
  5903. result.m[3] = 0.0;
  5904. result.m[4] = yaxis.x;
  5905. result.m[5] = yaxis.y;
  5906. result.m[6] = yaxis.z;
  5907. result.m[7] = 0.0;
  5908. result.m[8] = zaxis.x;
  5909. result.m[9] = zaxis.y;
  5910. result.m[10] = zaxis.z;
  5911. result.m[11] = 0.0;
  5912. result.m[12] = 0.0;
  5913. result.m[13] = 0.0;
  5914. result.m[14] = 0.0;
  5915. result.m[15] = 1.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5920. */
  5921. Matrix.FromQuaternionToRef = function (quat, result) {
  5922. var xx = quat.x * quat.x;
  5923. var yy = quat.y * quat.y;
  5924. var zz = quat.z * quat.z;
  5925. var xy = quat.x * quat.y;
  5926. var zw = quat.z * quat.w;
  5927. var zx = quat.z * quat.x;
  5928. var yw = quat.y * quat.w;
  5929. var yz = quat.y * quat.z;
  5930. var xw = quat.x * quat.w;
  5931. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5932. result.m[1] = 2.0 * (xy + zw);
  5933. result.m[2] = 2.0 * (zx - yw);
  5934. result.m[3] = 0.0;
  5935. result.m[4] = 2.0 * (xy - zw);
  5936. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5937. result.m[6] = 2.0 * (yz + xw);
  5938. result.m[7] = 0.0;
  5939. result.m[8] = 2.0 * (zx + yw);
  5940. result.m[9] = 2.0 * (yz - xw);
  5941. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5942. result.m[11] = 0.0;
  5943. result.m[12] = 0.0;
  5944. result.m[13] = 0.0;
  5945. result.m[14] = 0.0;
  5946. result.m[15] = 1.0;
  5947. result._markAsUpdated();
  5948. };
  5949. Matrix._tempQuaternion = new Quaternion();
  5950. Matrix._xAxis = Vector3.Zero();
  5951. Matrix._yAxis = Vector3.Zero();
  5952. Matrix._zAxis = Vector3.Zero();
  5953. Matrix._updateFlagSeed = 0;
  5954. Matrix._identityReadOnly = Matrix.Identity();
  5955. return Matrix;
  5956. }());
  5957. BABYLON.Matrix = Matrix;
  5958. var Plane = /** @class */ (function () {
  5959. /**
  5960. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5961. */
  5962. function Plane(a, b, c, d) {
  5963. this.normal = new Vector3(a, b, c);
  5964. this.d = d;
  5965. }
  5966. /**
  5967. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5968. */
  5969. Plane.prototype.asArray = function () {
  5970. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5971. };
  5972. // Methods
  5973. /**
  5974. * Returns a new plane copied from the current Plane.
  5975. */
  5976. Plane.prototype.clone = function () {
  5977. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5978. };
  5979. /**
  5980. * Returns the string "Plane".
  5981. */
  5982. Plane.prototype.getClassName = function () {
  5983. return "Plane";
  5984. };
  5985. /**
  5986. * Returns the Plane hash code.
  5987. */
  5988. Plane.prototype.getHashCode = function () {
  5989. var hash = this.normal.getHashCode();
  5990. hash = (hash * 397) ^ (this.d || 0);
  5991. return hash;
  5992. };
  5993. /**
  5994. * Normalize the current Plane in place.
  5995. * Returns the updated Plane.
  5996. */
  5997. Plane.prototype.normalize = function () {
  5998. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5999. var magnitude = 0.0;
  6000. if (norm !== 0) {
  6001. magnitude = 1.0 / norm;
  6002. }
  6003. this.normal.x *= magnitude;
  6004. this.normal.y *= magnitude;
  6005. this.normal.z *= magnitude;
  6006. this.d *= magnitude;
  6007. return this;
  6008. };
  6009. /**
  6010. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6011. */
  6012. Plane.prototype.transform = function (transformation) {
  6013. var transposedMatrix = Matrix.Transpose(transformation);
  6014. var x = this.normal.x;
  6015. var y = this.normal.y;
  6016. var z = this.normal.z;
  6017. var d = this.d;
  6018. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6019. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6020. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6021. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6022. return new Plane(normalX, normalY, normalZ, finalD);
  6023. };
  6024. /**
  6025. * Returns the dot product (float) of the point coordinates and the plane normal.
  6026. */
  6027. Plane.prototype.dotCoordinate = function (point) {
  6028. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6029. };
  6030. /**
  6031. * Updates the current Plane from the plane defined by the three passed points.
  6032. * Returns the updated Plane.
  6033. */
  6034. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6035. var x1 = point2.x - point1.x;
  6036. var y1 = point2.y - point1.y;
  6037. var z1 = point2.z - point1.z;
  6038. var x2 = point3.x - point1.x;
  6039. var y2 = point3.y - point1.y;
  6040. var z2 = point3.z - point1.z;
  6041. var yz = (y1 * z2) - (z1 * y2);
  6042. var xz = (z1 * x2) - (x1 * z2);
  6043. var xy = (x1 * y2) - (y1 * x2);
  6044. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6045. var invPyth;
  6046. if (pyth !== 0) {
  6047. invPyth = 1.0 / pyth;
  6048. }
  6049. else {
  6050. invPyth = 0.0;
  6051. }
  6052. this.normal.x = yz * invPyth;
  6053. this.normal.y = xz * invPyth;
  6054. this.normal.z = xy * invPyth;
  6055. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6056. return this;
  6057. };
  6058. /**
  6059. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6060. */
  6061. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6062. var dot = Vector3.Dot(this.normal, direction);
  6063. return (dot <= epsilon);
  6064. };
  6065. /**
  6066. * Returns the signed distance (float) from the passed point to the Plane.
  6067. */
  6068. Plane.prototype.signedDistanceTo = function (point) {
  6069. return Vector3.Dot(point, this.normal) + this.d;
  6070. };
  6071. // Statics
  6072. /**
  6073. * Returns a new Plane from the passed array.
  6074. */
  6075. Plane.FromArray = function (array) {
  6076. return new Plane(array[0], array[1], array[2], array[3]);
  6077. };
  6078. /**
  6079. * Returns a new Plane defined by the three passed points.
  6080. */
  6081. Plane.FromPoints = function (point1, point2, point3) {
  6082. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6083. result.copyFromPoints(point1, point2, point3);
  6084. return result;
  6085. };
  6086. /**
  6087. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6088. * Note : the vector "normal" is updated because normalized.
  6089. */
  6090. Plane.FromPositionAndNormal = function (origin, normal) {
  6091. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6092. normal.normalize();
  6093. result.normal = normal;
  6094. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6095. return result;
  6096. };
  6097. /**
  6098. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6099. */
  6100. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6101. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6102. return Vector3.Dot(point, normal) + d;
  6103. };
  6104. return Plane;
  6105. }());
  6106. BABYLON.Plane = Plane;
  6107. var Viewport = /** @class */ (function () {
  6108. /**
  6109. * Creates a Viewport object located at (x, y) and sized (width, height).
  6110. */
  6111. function Viewport(x, y, width, height) {
  6112. this.x = x;
  6113. this.y = y;
  6114. this.width = width;
  6115. this.height = height;
  6116. }
  6117. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6118. if (renderWidthOrEngine.getRenderWidth) {
  6119. var engine = renderWidthOrEngine;
  6120. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6121. }
  6122. var renderWidth = renderWidthOrEngine;
  6123. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6124. };
  6125. /**
  6126. * Returns a new Viewport copied from the current one.
  6127. */
  6128. Viewport.prototype.clone = function () {
  6129. return new Viewport(this.x, this.y, this.width, this.height);
  6130. };
  6131. return Viewport;
  6132. }());
  6133. BABYLON.Viewport = Viewport;
  6134. var Frustum = /** @class */ (function () {
  6135. function Frustum() {
  6136. }
  6137. /**
  6138. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6139. */
  6140. Frustum.GetPlanes = function (transform) {
  6141. var frustumPlanes = [];
  6142. for (var index = 0; index < 6; index++) {
  6143. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6144. }
  6145. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6146. return frustumPlanes;
  6147. };
  6148. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6149. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6150. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6151. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6152. frustumPlane.d = transform.m[15] + transform.m[14];
  6153. frustumPlane.normalize();
  6154. };
  6155. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6156. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6157. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6158. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6159. frustumPlane.d = transform.m[15] - transform.m[14];
  6160. frustumPlane.normalize();
  6161. };
  6162. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6163. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6164. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6165. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6166. frustumPlane.d = transform.m[15] + transform.m[12];
  6167. frustumPlane.normalize();
  6168. };
  6169. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6170. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6171. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6172. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6173. frustumPlane.d = transform.m[15] - transform.m[12];
  6174. frustumPlane.normalize();
  6175. };
  6176. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6177. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6178. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6179. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6180. frustumPlane.d = transform.m[15] - transform.m[13];
  6181. frustumPlane.normalize();
  6182. };
  6183. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6184. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6185. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6186. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6187. frustumPlane.d = transform.m[15] + transform.m[13];
  6188. frustumPlane.normalize();
  6189. };
  6190. /**
  6191. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6192. */
  6193. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6194. // Near
  6195. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6196. // Far
  6197. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6198. // Left
  6199. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6200. // Right
  6201. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6202. // Top
  6203. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6204. // Bottom
  6205. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6206. };
  6207. return Frustum;
  6208. }());
  6209. BABYLON.Frustum = Frustum;
  6210. var Space;
  6211. (function (Space) {
  6212. Space[Space["LOCAL"] = 0] = "LOCAL";
  6213. Space[Space["WORLD"] = 1] = "WORLD";
  6214. Space[Space["BONE"] = 2] = "BONE";
  6215. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6216. var Axis = /** @class */ (function () {
  6217. function Axis() {
  6218. }
  6219. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6220. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6222. return Axis;
  6223. }());
  6224. BABYLON.Axis = Axis;
  6225. ;
  6226. var BezierCurve = /** @class */ (function () {
  6227. function BezierCurve() {
  6228. }
  6229. /**
  6230. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6231. */
  6232. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6233. // Extract X (which is equal to time here)
  6234. var f0 = 1 - 3 * x2 + 3 * x1;
  6235. var f1 = 3 * x2 - 6 * x1;
  6236. var f2 = 3 * x1;
  6237. var refinedT = t;
  6238. for (var i = 0; i < 5; i++) {
  6239. var refinedT2 = refinedT * refinedT;
  6240. var refinedT3 = refinedT2 * refinedT;
  6241. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6242. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6243. refinedT -= (x - t) * slope;
  6244. refinedT = Math.min(1, Math.max(0, refinedT));
  6245. }
  6246. // Resolve cubic bezier for the given x
  6247. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6248. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6249. Math.pow(refinedT, 3);
  6250. };
  6251. return BezierCurve;
  6252. }());
  6253. BABYLON.BezierCurve = BezierCurve;
  6254. var Orientation;
  6255. (function (Orientation) {
  6256. Orientation[Orientation["CW"] = 0] = "CW";
  6257. Orientation[Orientation["CCW"] = 1] = "CCW";
  6258. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6259. var Angle = /** @class */ (function () {
  6260. /**
  6261. * Creates an Angle object of "radians" radians (float).
  6262. */
  6263. function Angle(radians) {
  6264. var _this = this;
  6265. /**
  6266. * Returns the Angle value in degrees (float).
  6267. */
  6268. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6269. /**
  6270. * Returns the Angle value in radians (float).
  6271. */
  6272. this.radians = function () { return _this._radians; };
  6273. this._radians = radians;
  6274. if (this._radians < 0.0)
  6275. this._radians += (2.0 * Math.PI);
  6276. }
  6277. /**
  6278. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6279. */
  6280. Angle.BetweenTwoPoints = function (a, b) {
  6281. var delta = b.subtract(a);
  6282. var theta = Math.atan2(delta.y, delta.x);
  6283. return new Angle(theta);
  6284. };
  6285. /**
  6286. * Returns a new Angle object from the passed float in radians.
  6287. */
  6288. Angle.FromRadians = function (radians) {
  6289. return new Angle(radians);
  6290. };
  6291. /**
  6292. * Returns a new Angle object from the passed float in degrees.
  6293. */
  6294. Angle.FromDegrees = function (degrees) {
  6295. return new Angle(degrees * Math.PI / 180.0);
  6296. };
  6297. return Angle;
  6298. }());
  6299. BABYLON.Angle = Angle;
  6300. var Arc2 = /** @class */ (function () {
  6301. /**
  6302. * Creates an Arc object from the three passed points : start, middle and end.
  6303. */
  6304. function Arc2(startPoint, midPoint, endPoint) {
  6305. this.startPoint = startPoint;
  6306. this.midPoint = midPoint;
  6307. this.endPoint = endPoint;
  6308. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6309. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6310. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6311. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6312. 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);
  6313. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6314. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6315. var a1 = this.startAngle.degrees();
  6316. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6317. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6318. // angles correction
  6319. if (a2 - a1 > +180.0)
  6320. a2 -= 360.0;
  6321. if (a2 - a1 < -180.0)
  6322. a2 += 360.0;
  6323. if (a3 - a2 > +180.0)
  6324. a3 -= 360.0;
  6325. if (a3 - a2 < -180.0)
  6326. a3 += 360.0;
  6327. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6328. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6329. }
  6330. return Arc2;
  6331. }());
  6332. BABYLON.Arc2 = Arc2;
  6333. var Path2 = /** @class */ (function () {
  6334. /**
  6335. * Creates a Path2 object from the starting 2D coordinates x and y.
  6336. */
  6337. function Path2(x, y) {
  6338. this._points = new Array();
  6339. this._length = 0.0;
  6340. this.closed = false;
  6341. this._points.push(new Vector2(x, y));
  6342. }
  6343. /**
  6344. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6345. * Returns the updated Path2.
  6346. */
  6347. Path2.prototype.addLineTo = function (x, y) {
  6348. if (this.closed) {
  6349. return this;
  6350. }
  6351. var newPoint = new Vector2(x, y);
  6352. var previousPoint = this._points[this._points.length - 1];
  6353. this._points.push(newPoint);
  6354. this._length += newPoint.subtract(previousPoint).length();
  6355. return this;
  6356. };
  6357. /**
  6358. * 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.
  6359. * Returns the updated Path2.
  6360. */
  6361. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6362. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6363. if (this.closed) {
  6364. return this;
  6365. }
  6366. var startPoint = this._points[this._points.length - 1];
  6367. var midPoint = new Vector2(midX, midY);
  6368. var endPoint = new Vector2(endX, endY);
  6369. var arc = new Arc2(startPoint, midPoint, endPoint);
  6370. var increment = arc.angle.radians() / numberOfSegments;
  6371. if (arc.orientation === Orientation.CW)
  6372. increment *= -1;
  6373. var currentAngle = arc.startAngle.radians() + increment;
  6374. for (var i = 0; i < numberOfSegments; i++) {
  6375. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6376. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6377. this.addLineTo(x, y);
  6378. currentAngle += increment;
  6379. }
  6380. return this;
  6381. };
  6382. /**
  6383. * Closes the Path2.
  6384. * Returns the Path2.
  6385. */
  6386. Path2.prototype.close = function () {
  6387. this.closed = true;
  6388. return this;
  6389. };
  6390. /**
  6391. * Returns the Path2 total length (float).
  6392. */
  6393. Path2.prototype.length = function () {
  6394. var result = this._length;
  6395. if (!this.closed) {
  6396. var lastPoint = this._points[this._points.length - 1];
  6397. var firstPoint = this._points[0];
  6398. result += (firstPoint.subtract(lastPoint).length());
  6399. }
  6400. return result;
  6401. };
  6402. /**
  6403. * Returns the Path2 internal array of points.
  6404. */
  6405. Path2.prototype.getPoints = function () {
  6406. return this._points;
  6407. };
  6408. /**
  6409. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6410. */
  6411. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6412. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6413. return Vector2.Zero();
  6414. }
  6415. var lengthPosition = normalizedLengthPosition * this.length();
  6416. var previousOffset = 0;
  6417. for (var i = 0; i < this._points.length; i++) {
  6418. var j = (i + 1) % this._points.length;
  6419. var a = this._points[i];
  6420. var b = this._points[j];
  6421. var bToA = b.subtract(a);
  6422. var nextOffset = (bToA.length() + previousOffset);
  6423. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6424. var dir = bToA.normalize();
  6425. var localOffset = lengthPosition - previousOffset;
  6426. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6427. }
  6428. previousOffset = nextOffset;
  6429. }
  6430. return Vector2.Zero();
  6431. };
  6432. /**
  6433. * Returns a new Path2 starting at the coordinates (x, y).
  6434. */
  6435. Path2.StartingAt = function (x, y) {
  6436. return new Path2(x, y);
  6437. };
  6438. return Path2;
  6439. }());
  6440. BABYLON.Path2 = Path2;
  6441. var Path3D = /** @class */ (function () {
  6442. /**
  6443. * new Path3D(path, normal, raw)
  6444. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6445. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6446. * path : an array of Vector3, the curve axis of the Path3D
  6447. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6448. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6449. */
  6450. function Path3D(path, firstNormal, raw) {
  6451. if (firstNormal === void 0) { firstNormal = null; }
  6452. this.path = path;
  6453. this._curve = new Array();
  6454. this._distances = new Array();
  6455. this._tangents = new Array();
  6456. this._normals = new Array();
  6457. this._binormals = new Array();
  6458. for (var p = 0; p < path.length; p++) {
  6459. this._curve[p] = path[p].clone(); // hard copy
  6460. }
  6461. this._raw = raw || false;
  6462. this._compute(firstNormal);
  6463. }
  6464. /**
  6465. * Returns the Path3D array of successive Vector3 designing its curve.
  6466. */
  6467. Path3D.prototype.getCurve = function () {
  6468. return this._curve;
  6469. };
  6470. /**
  6471. * Returns an array populated with tangent vectors on each Path3D curve point.
  6472. */
  6473. Path3D.prototype.getTangents = function () {
  6474. return this._tangents;
  6475. };
  6476. /**
  6477. * Returns an array populated with normal vectors on each Path3D curve point.
  6478. */
  6479. Path3D.prototype.getNormals = function () {
  6480. return this._normals;
  6481. };
  6482. /**
  6483. * Returns an array populated with binormal vectors on each Path3D curve point.
  6484. */
  6485. Path3D.prototype.getBinormals = function () {
  6486. return this._binormals;
  6487. };
  6488. /**
  6489. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6490. */
  6491. Path3D.prototype.getDistances = function () {
  6492. return this._distances;
  6493. };
  6494. /**
  6495. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6496. * Returns the same object updated.
  6497. */
  6498. Path3D.prototype.update = function (path, firstNormal) {
  6499. if (firstNormal === void 0) { firstNormal = null; }
  6500. for (var p = 0; p < path.length; p++) {
  6501. this._curve[p].x = path[p].x;
  6502. this._curve[p].y = path[p].y;
  6503. this._curve[p].z = path[p].z;
  6504. }
  6505. this._compute(firstNormal);
  6506. return this;
  6507. };
  6508. // private function compute() : computes tangents, normals and binormals
  6509. Path3D.prototype._compute = function (firstNormal) {
  6510. var l = this._curve.length;
  6511. // first and last tangents
  6512. this._tangents[0] = this._getFirstNonNullVector(0);
  6513. if (!this._raw) {
  6514. this._tangents[0].normalize();
  6515. }
  6516. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6517. if (!this._raw) {
  6518. this._tangents[l - 1].normalize();
  6519. }
  6520. // normals and binormals at first point : arbitrary vector with _normalVector()
  6521. var tg0 = this._tangents[0];
  6522. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6523. this._normals[0] = pp0;
  6524. if (!this._raw) {
  6525. this._normals[0].normalize();
  6526. }
  6527. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6528. if (!this._raw) {
  6529. this._binormals[0].normalize();
  6530. }
  6531. this._distances[0] = 0.0;
  6532. // normals and binormals : next points
  6533. var prev; // previous vector (segment)
  6534. var cur; // current vector (segment)
  6535. var curTang; // current tangent
  6536. // previous normal
  6537. var prevBinor; // previous binormal
  6538. for (var i = 1; i < l; i++) {
  6539. // tangents
  6540. prev = this._getLastNonNullVector(i);
  6541. if (i < l - 1) {
  6542. cur = this._getFirstNonNullVector(i);
  6543. this._tangents[i] = prev.add(cur);
  6544. this._tangents[i].normalize();
  6545. }
  6546. this._distances[i] = this._distances[i - 1] + prev.length();
  6547. // normals and binormals
  6548. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6549. curTang = this._tangents[i];
  6550. prevBinor = this._binormals[i - 1];
  6551. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6552. if (!this._raw) {
  6553. this._normals[i].normalize();
  6554. }
  6555. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6556. if (!this._raw) {
  6557. this._binormals[i].normalize();
  6558. }
  6559. }
  6560. };
  6561. // private function getFirstNonNullVector(index)
  6562. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6563. Path3D.prototype._getFirstNonNullVector = function (index) {
  6564. var i = 1;
  6565. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6566. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6567. i++;
  6568. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6569. }
  6570. return nNVector;
  6571. };
  6572. // private function getLastNonNullVector(index)
  6573. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6574. Path3D.prototype._getLastNonNullVector = function (index) {
  6575. var i = 1;
  6576. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6577. while (nLVector.length() === 0 && index > i + 1) {
  6578. i++;
  6579. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6580. }
  6581. return nLVector;
  6582. };
  6583. // private function normalVector(v0, vt, va) :
  6584. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6585. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6586. Path3D.prototype._normalVector = function (v0, vt, va) {
  6587. var normal0;
  6588. var tgl = vt.length();
  6589. if (tgl === 0.0) {
  6590. tgl = 1.0;
  6591. }
  6592. if (va === undefined || va === null) {
  6593. var point;
  6594. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6595. point = new Vector3(0.0, -1.0, 0.0);
  6596. }
  6597. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6598. point = new Vector3(1.0, 0.0, 0.0);
  6599. }
  6600. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6601. point = new Vector3(0.0, 0.0, 1.0);
  6602. }
  6603. else {
  6604. point = Vector3.Zero();
  6605. }
  6606. normal0 = Vector3.Cross(vt, point);
  6607. }
  6608. else {
  6609. normal0 = Vector3.Cross(vt, va);
  6610. Vector3.CrossToRef(normal0, vt, normal0);
  6611. }
  6612. normal0.normalize();
  6613. return normal0;
  6614. };
  6615. return Path3D;
  6616. }());
  6617. BABYLON.Path3D = Path3D;
  6618. var Curve3 = /** @class */ (function () {
  6619. /**
  6620. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6621. * A Curve3 is designed from a series of successive Vector3.
  6622. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6623. */
  6624. function Curve3(points) {
  6625. this._length = 0.0;
  6626. this._points = points;
  6627. this._length = this._computeLength(points);
  6628. }
  6629. /**
  6630. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6631. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6632. * @param v1 (Vector3) the control point
  6633. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6634. * @param nbPoints (integer) the wanted number of points in the curve
  6635. */
  6636. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6637. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6638. var bez = new Array();
  6639. var equation = function (t, val0, val1, val2) {
  6640. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6641. return res;
  6642. };
  6643. for (var i = 0; i <= nbPoints; i++) {
  6644. 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)));
  6645. }
  6646. return new Curve3(bez);
  6647. };
  6648. /**
  6649. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6650. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6651. * @param v1 (Vector3) the first control point
  6652. * @param v2 (Vector3) the second control point
  6653. * @param v3 (Vector3) the end point of the Cubic Bezier
  6654. * @param nbPoints (integer) the wanted number of points in the curve
  6655. */
  6656. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6657. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6658. var bez = new Array();
  6659. var equation = function (t, val0, val1, val2, val3) {
  6660. 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;
  6661. return res;
  6662. };
  6663. for (var i = 0; i <= nbPoints; i++) {
  6664. 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)));
  6665. }
  6666. return new Curve3(bez);
  6667. };
  6668. /**
  6669. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6670. * @param p1 (Vector3) the origin point of the Hermite Spline
  6671. * @param t1 (Vector3) the tangent vector at the origin point
  6672. * @param p2 (Vector3) the end point of the Hermite Spline
  6673. * @param t2 (Vector3) the tangent vector at the end point
  6674. * @param nbPoints (integer) the wanted number of points in the curve
  6675. */
  6676. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6677. var hermite = new Array();
  6678. var step = 1.0 / nbPoints;
  6679. for (var i = 0; i <= nbPoints; i++) {
  6680. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6681. }
  6682. return new Curve3(hermite);
  6683. };
  6684. /**
  6685. * Returns a Curve3 object along a CatmullRom Spline curve :
  6686. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6687. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6688. */
  6689. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6690. var totalPoints = new Array();
  6691. totalPoints.push(points[0].clone());
  6692. Array.prototype.push.apply(totalPoints, points);
  6693. totalPoints.push(points[points.length - 1].clone());
  6694. var catmullRom = new Array();
  6695. var step = 1.0 / nbPoints;
  6696. var amount = 0.0;
  6697. for (var i = 0; i < totalPoints.length - 3; i++) {
  6698. amount = 0;
  6699. for (var c = 0; c < nbPoints; c++) {
  6700. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6701. amount += step;
  6702. }
  6703. }
  6704. i--;
  6705. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6706. return new Curve3(catmullRom);
  6707. };
  6708. /**
  6709. * Returns the Curve3 stored array of successive Vector3
  6710. */
  6711. Curve3.prototype.getPoints = function () {
  6712. return this._points;
  6713. };
  6714. /**
  6715. * Returns the computed length (float) of the curve.
  6716. */
  6717. Curve3.prototype.length = function () {
  6718. return this._length;
  6719. };
  6720. /**
  6721. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6722. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6723. * curveA and curveB keep unchanged.
  6724. */
  6725. Curve3.prototype.continue = function (curve) {
  6726. var lastPoint = this._points[this._points.length - 1];
  6727. var continuedPoints = this._points.slice();
  6728. var curvePoints = curve.getPoints();
  6729. for (var i = 1; i < curvePoints.length; i++) {
  6730. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6731. }
  6732. var continuedCurve = new Curve3(continuedPoints);
  6733. return continuedCurve;
  6734. };
  6735. Curve3.prototype._computeLength = function (path) {
  6736. var l = 0;
  6737. for (var i = 1; i < path.length; i++) {
  6738. l += (path[i].subtract(path[i - 1])).length();
  6739. }
  6740. return l;
  6741. };
  6742. return Curve3;
  6743. }());
  6744. BABYLON.Curve3 = Curve3;
  6745. // Vertex formats
  6746. var PositionNormalVertex = /** @class */ (function () {
  6747. function PositionNormalVertex(position, normal) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. this.position = position;
  6751. this.normal = normal;
  6752. }
  6753. PositionNormalVertex.prototype.clone = function () {
  6754. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6755. };
  6756. return PositionNormalVertex;
  6757. }());
  6758. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6759. var PositionNormalTextureVertex = /** @class */ (function () {
  6760. function PositionNormalTextureVertex(position, normal, uv) {
  6761. if (position === void 0) { position = Vector3.Zero(); }
  6762. if (normal === void 0) { normal = Vector3.Up(); }
  6763. if (uv === void 0) { uv = Vector2.Zero(); }
  6764. this.position = position;
  6765. this.normal = normal;
  6766. this.uv = uv;
  6767. }
  6768. PositionNormalTextureVertex.prototype.clone = function () {
  6769. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6770. };
  6771. return PositionNormalTextureVertex;
  6772. }());
  6773. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6774. // Temporary pre-allocated objects for engine internal use
  6775. // usage in any internal function :
  6776. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6777. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6778. var Tmp = /** @class */ (function () {
  6779. function Tmp() {
  6780. }
  6781. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6782. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6783. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6784. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6785. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6786. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6787. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6788. Matrix.Zero(), Matrix.Zero(),
  6789. Matrix.Zero(), Matrix.Zero(),
  6790. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6791. return Tmp;
  6792. }());
  6793. BABYLON.Tmp = Tmp;
  6794. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6795. var MathTmp = /** @class */ (function () {
  6796. function MathTmp() {
  6797. }
  6798. MathTmp.Vector3 = [Vector3.Zero()];
  6799. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6800. MathTmp.Quaternion = [Quaternion.Zero()];
  6801. return MathTmp;
  6802. }());
  6803. })(BABYLON || (BABYLON = {}));
  6804. //# sourceMappingURL=babylon.math.js.map
  6805. "use strict";
  6806. var BABYLON;
  6807. (function (BABYLON) {
  6808. var Scalar = /** @class */ (function () {
  6809. function Scalar() {
  6810. }
  6811. /**
  6812. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6813. */
  6814. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6815. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6816. var num = a - b;
  6817. return -epsilon <= num && num <= epsilon;
  6818. };
  6819. /**
  6820. * Returns a string : the upper case translation of the number i to hexadecimal.
  6821. */
  6822. Scalar.ToHex = function (i) {
  6823. var str = i.toString(16);
  6824. if (i <= 15) {
  6825. return ("0" + str).toUpperCase();
  6826. }
  6827. return str.toUpperCase();
  6828. };
  6829. /**
  6830. * Returns -1 if value is negative and +1 is value is positive.
  6831. * Returns the value itself if it's equal to zero.
  6832. */
  6833. Scalar.Sign = function (value) {
  6834. value = +value; // convert to a number
  6835. if (value === 0 || isNaN(value))
  6836. return value;
  6837. return value > 0 ? 1 : -1;
  6838. };
  6839. /**
  6840. * Returns the value itself if it's between min and max.
  6841. * Returns min if the value is lower than min.
  6842. * Returns max if the value is greater than max.
  6843. */
  6844. Scalar.Clamp = function (value, min, max) {
  6845. if (min === void 0) { min = 0; }
  6846. if (max === void 0) { max = 1; }
  6847. return Math.min(max, Math.max(min, value));
  6848. };
  6849. /**
  6850. * Returns the log2 of value.
  6851. */
  6852. Scalar.Log2 = function (value) {
  6853. return Math.log(value) * Math.LOG2E;
  6854. };
  6855. /**
  6856. * Loops the value, so that it is never larger than length and never smaller than 0.
  6857. *
  6858. * This is similar to the modulo operator but it works with floating point numbers.
  6859. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6860. * With t = 5 and length = 2.5, the result would be 0.0.
  6861. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6862. */
  6863. Scalar.Repeat = function (value, length) {
  6864. return value - Math.floor(value / length) * length;
  6865. };
  6866. /**
  6867. * Normalize the value between 0.0 and 1.0 using min and max values
  6868. */
  6869. Scalar.Normalize = function (value, min, max) {
  6870. return (value - min) / (max - min);
  6871. };
  6872. /**
  6873. * Denormalize the value from 0.0 and 1.0 using min and max values
  6874. */
  6875. Scalar.Denormalize = function (normalized, min, max) {
  6876. return (normalized * (max - min) + min);
  6877. };
  6878. /**
  6879. * Calculates the shortest difference between two given angles given in degrees.
  6880. */
  6881. Scalar.DeltaAngle = function (current, target) {
  6882. var num = Scalar.Repeat(target - current, 360.0);
  6883. if (num > 180.0) {
  6884. num -= 360.0;
  6885. }
  6886. return num;
  6887. };
  6888. /**
  6889. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6890. *
  6891. * The returned value will move back and forth between 0 and length
  6892. */
  6893. Scalar.PingPong = function (tx, length) {
  6894. var t = Scalar.Repeat(tx, length * 2.0);
  6895. return length - Math.abs(t - length);
  6896. };
  6897. /**
  6898. * Interpolates between min and max with smoothing at the limits.
  6899. *
  6900. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6901. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6902. */
  6903. Scalar.SmoothStep = function (from, to, tx) {
  6904. var t = Scalar.Clamp(tx);
  6905. t = -2.0 * t * t * t + 3.0 * t * t;
  6906. return to * t + from * (1.0 - t);
  6907. };
  6908. /**
  6909. * Moves a value current towards target.
  6910. *
  6911. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6912. * Negative values of maxDelta pushes the value away from target.
  6913. */
  6914. Scalar.MoveTowards = function (current, target, maxDelta) {
  6915. var result = 0;
  6916. if (Math.abs(target - current) <= maxDelta) {
  6917. result = target;
  6918. }
  6919. else {
  6920. result = current + Scalar.Sign(target - current) * maxDelta;
  6921. }
  6922. return result;
  6923. };
  6924. /**
  6925. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6926. *
  6927. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6928. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6929. */
  6930. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6931. var num = Scalar.DeltaAngle(current, target);
  6932. var result = 0;
  6933. if (-maxDelta < num && num < maxDelta) {
  6934. result = target;
  6935. }
  6936. else {
  6937. target = current + num;
  6938. result = Scalar.MoveTowards(current, target, maxDelta);
  6939. }
  6940. return result;
  6941. };
  6942. /**
  6943. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6944. */
  6945. Scalar.Lerp = function (start, end, amount) {
  6946. return start + ((end - start) * amount);
  6947. };
  6948. /**
  6949. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6950. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6951. */
  6952. Scalar.LerpAngle = function (start, end, amount) {
  6953. var num = Scalar.Repeat(end - start, 360.0);
  6954. if (num > 180.0) {
  6955. num -= 360.0;
  6956. }
  6957. return start + num * Scalar.Clamp(amount);
  6958. };
  6959. /**
  6960. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6961. */
  6962. Scalar.InverseLerp = function (a, b, value) {
  6963. var result = 0;
  6964. if (a != b) {
  6965. result = Scalar.Clamp((value - a) / (b - a));
  6966. }
  6967. else {
  6968. result = 0.0;
  6969. }
  6970. return result;
  6971. };
  6972. /**
  6973. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6974. */
  6975. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6976. var squared = amount * amount;
  6977. var cubed = amount * squared;
  6978. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6979. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6980. var part3 = (cubed - (2.0 * squared)) + amount;
  6981. var part4 = cubed - squared;
  6982. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6983. };
  6984. /**
  6985. * Returns a random float number between and min and max values
  6986. */
  6987. Scalar.RandomRange = function (min, max) {
  6988. if (min === max)
  6989. return min;
  6990. return ((Math.random() * (max - min)) + min);
  6991. };
  6992. /**
  6993. * This function returns percentage of a number in a given range.
  6994. *
  6995. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6996. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6997. */
  6998. Scalar.RangeToPercent = function (number, min, max) {
  6999. return ((number - min) / (max - min));
  7000. };
  7001. /**
  7002. * This function returns number that corresponds to the percentage in a given range.
  7003. *
  7004. * PercentToRange(0.34,0,100) will return 34.
  7005. */
  7006. Scalar.PercentToRange = function (percent, min, max) {
  7007. return ((max - min) * percent + min);
  7008. };
  7009. /**
  7010. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7011. * @param angle The angle to normalize in radian.
  7012. * @return The converted angle.
  7013. */
  7014. Scalar.NormalizeRadians = function (angle) {
  7015. // More precise but slower version kept for reference.
  7016. // angle = angle % Tools.TwoPi;
  7017. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7018. //if (angle > Math.PI) {
  7019. // angle -= Tools.TwoPi;
  7020. //}
  7021. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7022. return angle;
  7023. };
  7024. /**
  7025. * Two pi constants convenient for computation.
  7026. */
  7027. Scalar.TwoPi = Math.PI * 2;
  7028. return Scalar;
  7029. }());
  7030. BABYLON.Scalar = Scalar;
  7031. })(BABYLON || (BABYLON = {}));
  7032. //# sourceMappingURL=babylon.math.scalar.js.map
  7033. "use strict";
  7034. //# sourceMappingURL=babylon.mixins.js.map
  7035. "use strict";
  7036. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7037. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7038. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7039. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7040. //# sourceMappingURL=babylon.webgl2.js.map
  7041. "use strict";
  7042. var BABYLON;
  7043. (function (BABYLON) {
  7044. var __decoratorInitialStore = {};
  7045. var __mergedStore = {};
  7046. var _copySource = function (creationFunction, source, instanciate) {
  7047. var destination = creationFunction();
  7048. // Tags
  7049. if (BABYLON.Tags) {
  7050. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7051. }
  7052. var classStore = getMergedStore(destination);
  7053. // Properties
  7054. for (var property in classStore) {
  7055. var propertyDescriptor = classStore[property];
  7056. var sourceProperty = source[property];
  7057. var propertyType = propertyDescriptor.type;
  7058. if (sourceProperty !== undefined && sourceProperty !== null) {
  7059. switch (propertyType) {
  7060. case 0: // Value
  7061. case 6:// Mesh reference
  7062. destination[property] = sourceProperty;
  7063. break;
  7064. case 1:// Texture
  7065. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7066. break;
  7067. case 2: // Color3
  7068. case 3: // FresnelParameters
  7069. case 4: // Vector2
  7070. case 5: // Vector3
  7071. case 7: // Color Curves
  7072. case 10:// Quaternion
  7073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7074. break;
  7075. }
  7076. }
  7077. }
  7078. return destination;
  7079. };
  7080. function getDirectStore(target) {
  7081. var classKey = target.getClassName();
  7082. if (!__decoratorInitialStore[classKey]) {
  7083. __decoratorInitialStore[classKey] = {};
  7084. }
  7085. return __decoratorInitialStore[classKey];
  7086. }
  7087. /**
  7088. * Return the list of properties flagged as serializable
  7089. * @param target: host object
  7090. */
  7091. function getMergedStore(target) {
  7092. var classKey = target.getClassName();
  7093. if (__mergedStore[classKey]) {
  7094. return __mergedStore[classKey];
  7095. }
  7096. __mergedStore[classKey] = {};
  7097. var store = __mergedStore[classKey];
  7098. var currentTarget = target;
  7099. var currentKey = classKey;
  7100. while (currentKey) {
  7101. var initialStore = __decoratorInitialStore[currentKey];
  7102. for (var property in initialStore) {
  7103. store[property] = initialStore[property];
  7104. }
  7105. var parent_1 = void 0;
  7106. var done = false;
  7107. do {
  7108. parent_1 = Object.getPrototypeOf(currentTarget);
  7109. if (!parent_1.getClassName) {
  7110. done = true;
  7111. break;
  7112. }
  7113. if (parent_1.getClassName() !== currentKey) {
  7114. break;
  7115. }
  7116. currentTarget = parent_1;
  7117. } while (parent_1);
  7118. if (done) {
  7119. break;
  7120. }
  7121. currentKey = parent_1.getClassName();
  7122. currentTarget = parent_1;
  7123. }
  7124. return store;
  7125. }
  7126. function generateSerializableMember(type, sourceName) {
  7127. return function (target, propertyKey) {
  7128. var classStore = getDirectStore(target);
  7129. if (!classStore[propertyKey]) {
  7130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7131. }
  7132. };
  7133. }
  7134. function generateExpandMember(setCallback, targetKey) {
  7135. if (targetKey === void 0) { targetKey = null; }
  7136. return function (target, propertyKey) {
  7137. var key = targetKey || ("_" + propertyKey);
  7138. Object.defineProperty(target, propertyKey, {
  7139. get: function () {
  7140. return this[key];
  7141. },
  7142. set: function (value) {
  7143. if (this[key] === value) {
  7144. return;
  7145. }
  7146. this[key] = value;
  7147. target[setCallback].apply(this);
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. };
  7153. }
  7154. function expandToProperty(callback, targetKey) {
  7155. if (targetKey === void 0) { targetKey = null; }
  7156. return generateExpandMember(callback, targetKey);
  7157. }
  7158. BABYLON.expandToProperty = expandToProperty;
  7159. function serialize(sourceName) {
  7160. return generateSerializableMember(0, sourceName); // value member
  7161. }
  7162. BABYLON.serialize = serialize;
  7163. function serializeAsTexture(sourceName) {
  7164. return generateSerializableMember(1, sourceName); // texture member
  7165. }
  7166. BABYLON.serializeAsTexture = serializeAsTexture;
  7167. function serializeAsColor3(sourceName) {
  7168. return generateSerializableMember(2, sourceName); // color3 member
  7169. }
  7170. BABYLON.serializeAsColor3 = serializeAsColor3;
  7171. function serializeAsFresnelParameters(sourceName) {
  7172. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7173. }
  7174. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7175. function serializeAsVector2(sourceName) {
  7176. return generateSerializableMember(4, sourceName); // vector2 member
  7177. }
  7178. BABYLON.serializeAsVector2 = serializeAsVector2;
  7179. function serializeAsVector3(sourceName) {
  7180. return generateSerializableMember(5, sourceName); // vector3 member
  7181. }
  7182. BABYLON.serializeAsVector3 = serializeAsVector3;
  7183. function serializeAsMeshReference(sourceName) {
  7184. return generateSerializableMember(6, sourceName); // mesh reference member
  7185. }
  7186. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7187. function serializeAsColorCurves(sourceName) {
  7188. return generateSerializableMember(7, sourceName); // color curves
  7189. }
  7190. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7191. function serializeAsColor4(sourceName) {
  7192. return generateSerializableMember(8, sourceName); // color 4
  7193. }
  7194. BABYLON.serializeAsColor4 = serializeAsColor4;
  7195. function serializeAsImageProcessingConfiguration(sourceName) {
  7196. return generateSerializableMember(9, sourceName); // image processing
  7197. }
  7198. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7199. function serializeAsQuaternion(sourceName) {
  7200. return generateSerializableMember(10, sourceName); // quaternion member
  7201. }
  7202. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7203. var SerializationHelper = /** @class */ (function () {
  7204. function SerializationHelper() {
  7205. }
  7206. SerializationHelper.Serialize = function (entity, serializationObject) {
  7207. if (!serializationObject) {
  7208. serializationObject = {};
  7209. }
  7210. // Tags
  7211. if (BABYLON.Tags) {
  7212. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7213. }
  7214. var serializedProperties = getMergedStore(entity);
  7215. // Properties
  7216. for (var property in serializedProperties) {
  7217. var propertyDescriptor = serializedProperties[property];
  7218. var targetPropertyName = propertyDescriptor.sourceName || property;
  7219. var propertyType = propertyDescriptor.type;
  7220. var sourceProperty = entity[property];
  7221. if (sourceProperty !== undefined && sourceProperty !== null) {
  7222. switch (propertyType) {
  7223. case 0:// Value
  7224. serializationObject[targetPropertyName] = sourceProperty;
  7225. break;
  7226. case 1:// Texture
  7227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7228. break;
  7229. case 2:// Color3
  7230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7231. break;
  7232. case 3:// FresnelParameters
  7233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7234. break;
  7235. case 4:// Vector2
  7236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7237. break;
  7238. case 5:// Vector3
  7239. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7240. break;
  7241. case 6:// Mesh reference
  7242. serializationObject[targetPropertyName] = sourceProperty.id;
  7243. break;
  7244. case 7:// Color Curves
  7245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7246. break;
  7247. case 8:// Color 4
  7248. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7249. break;
  7250. case 9:// Image Processing
  7251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7252. break;
  7253. }
  7254. }
  7255. }
  7256. return serializationObject;
  7257. };
  7258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7259. if (rootUrl === void 0) { rootUrl = null; }
  7260. var destination = creationFunction();
  7261. if (!rootUrl) {
  7262. rootUrl = "";
  7263. }
  7264. // Tags
  7265. if (BABYLON.Tags) {
  7266. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7267. }
  7268. var classStore = getMergedStore(destination);
  7269. // Properties
  7270. for (var property in classStore) {
  7271. var propertyDescriptor = classStore[property];
  7272. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7273. var propertyType = propertyDescriptor.type;
  7274. if (sourceProperty !== undefined && sourceProperty !== null) {
  7275. var dest = destination;
  7276. switch (propertyType) {
  7277. case 0:// Value
  7278. dest[property] = sourceProperty;
  7279. break;
  7280. case 1:// Texture
  7281. if (scene) {
  7282. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7283. }
  7284. break;
  7285. case 2:// Color3
  7286. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7287. break;
  7288. case 3:// FresnelParameters
  7289. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7290. break;
  7291. case 4:// Vector2
  7292. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7293. break;
  7294. case 5:// Vector3
  7295. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7296. break;
  7297. case 6:// Mesh reference
  7298. if (scene) {
  7299. dest[property] = scene.getLastMeshByID(sourceProperty);
  7300. }
  7301. break;
  7302. case 7:// Color Curves
  7303. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7304. break;
  7305. case 8:// Color 4
  7306. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7307. break;
  7308. case 9:// Image Processing
  7309. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7310. break;
  7311. }
  7312. }
  7313. }
  7314. return destination;
  7315. };
  7316. SerializationHelper.Clone = function (creationFunction, source) {
  7317. return _copySource(creationFunction, source, false);
  7318. };
  7319. SerializationHelper.Instanciate = function (creationFunction, source) {
  7320. return _copySource(creationFunction, source, true);
  7321. };
  7322. return SerializationHelper;
  7323. }());
  7324. BABYLON.SerializationHelper = SerializationHelper;
  7325. })(BABYLON || (BABYLON = {}));
  7326. //# sourceMappingURL=babylon.decorators.js.map
  7327. "use strict";
  7328. var BABYLON;
  7329. (function (BABYLON) {
  7330. /**
  7331. * Wrapper class for promise with external resolve and reject.
  7332. */
  7333. var Deferred = /** @class */ (function () {
  7334. /**
  7335. * Constructor for this deferred object.
  7336. */
  7337. function Deferred() {
  7338. var _this = this;
  7339. this.promise = new Promise(function (resolve, reject) {
  7340. _this._resolve = resolve;
  7341. _this._reject = reject;
  7342. });
  7343. }
  7344. Object.defineProperty(Deferred.prototype, "resolve", {
  7345. /**
  7346. * The resolve method of the promise associated with this deferred object.
  7347. */
  7348. get: function () {
  7349. return this._resolve;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Deferred.prototype, "reject", {
  7355. /**
  7356. * The reject method of the promise associated with this deferred object.
  7357. */
  7358. get: function () {
  7359. return this._reject;
  7360. },
  7361. enumerable: true,
  7362. configurable: true
  7363. });
  7364. return Deferred;
  7365. }());
  7366. BABYLON.Deferred = Deferred;
  7367. })(BABYLON || (BABYLON = {}));
  7368. //# sourceMappingURL=babylon.deferred.js.map
  7369. "use strict";
  7370. var BABYLON;
  7371. (function (BABYLON) {
  7372. /**
  7373. * A class serves as a medium between the observable and its observers
  7374. */
  7375. var EventState = /** @class */ (function () {
  7376. /**
  7377. * Create a new EventState
  7378. * @param mask defines the mask associated with this state
  7379. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7380. * @param target defines the original target of the state
  7381. * @param currentTarget defines the current target of the state
  7382. */
  7383. function EventState(mask, skipNextObservers, target, currentTarget) {
  7384. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7385. this.initalize(mask, skipNextObservers, target, currentTarget);
  7386. }
  7387. /**
  7388. * Initialize the current event state
  7389. * @param mask defines the mask associated with this state
  7390. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7391. * @param target defines the original target of the state
  7392. * @param currentTarget defines the current target of the state
  7393. * @returns the current event state
  7394. */
  7395. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7396. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7397. this.mask = mask;
  7398. this.skipNextObservers = skipNextObservers;
  7399. this.target = target;
  7400. this.currentTarget = currentTarget;
  7401. return this;
  7402. };
  7403. return EventState;
  7404. }());
  7405. BABYLON.EventState = EventState;
  7406. /**
  7407. * Represent an Observer registered to a given Observable object.
  7408. */
  7409. var Observer = /** @class */ (function () {
  7410. /**
  7411. * Creates a new observer
  7412. * @param callback defines the callback to call when the observer is notified
  7413. * @param mask defines the mask of the observer (used to filter notifications)
  7414. * @param scope defines the current scope used to restore the JS context
  7415. */
  7416. function Observer(
  7417. /**
  7418. * Defines the callback to call when the observer is notified
  7419. */
  7420. callback,
  7421. /**
  7422. * Defines the mask of the observer (used to filter notifications)
  7423. */
  7424. mask,
  7425. /**
  7426. * Defines the current scope used to restore the JS context
  7427. */
  7428. scope) {
  7429. if (scope === void 0) { scope = null; }
  7430. this.callback = callback;
  7431. this.mask = mask;
  7432. this.scope = scope;
  7433. /** @ignore */
  7434. this._willBeUnregistered = false;
  7435. /**
  7436. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7437. */
  7438. this.unregisterOnNextCall = false;
  7439. }
  7440. return Observer;
  7441. }());
  7442. BABYLON.Observer = Observer;
  7443. /**
  7444. * Represent a list of observers registered to multiple Observables object.
  7445. */
  7446. var MultiObserver = /** @class */ (function () {
  7447. function MultiObserver() {
  7448. }
  7449. /**
  7450. * Release associated resources
  7451. */
  7452. MultiObserver.prototype.dispose = function () {
  7453. if (this._observers && this._observables) {
  7454. for (var index = 0; index < this._observers.length; index++) {
  7455. this._observables[index].remove(this._observers[index]);
  7456. }
  7457. }
  7458. this._observers = null;
  7459. this._observables = null;
  7460. };
  7461. /**
  7462. * Raise a callback when one of the observable will notify
  7463. * @param observables defines a list of observables to watch
  7464. * @param callback defines the callback to call on notification
  7465. * @param mask defines the mask used to filter notifications
  7466. * @param scope defines the current scope used to restore the JS context
  7467. * @returns the new MultiObserver
  7468. */
  7469. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7470. if (mask === void 0) { mask = -1; }
  7471. if (scope === void 0) { scope = null; }
  7472. var result = new MultiObserver();
  7473. result._observers = new Array();
  7474. result._observables = observables;
  7475. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7476. var observable = observables_1[_i];
  7477. var observer = observable.add(callback, mask, false, scope);
  7478. if (observer) {
  7479. result._observers.push(observer);
  7480. }
  7481. }
  7482. return result;
  7483. };
  7484. return MultiObserver;
  7485. }());
  7486. BABYLON.MultiObserver = MultiObserver;
  7487. /**
  7488. * The Observable class is a simple implementation of the Observable pattern.
  7489. *
  7490. * 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.
  7491. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7492. * 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).
  7493. * 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.
  7494. */
  7495. var Observable = /** @class */ (function () {
  7496. /**
  7497. * Creates a new observable
  7498. * @param onObserverAdded defines a callback to call when a new observer is added
  7499. */
  7500. function Observable(onObserverAdded) {
  7501. this._observers = new Array();
  7502. this._eventState = new EventState(0);
  7503. if (onObserverAdded) {
  7504. this._onObserverAdded = onObserverAdded;
  7505. }
  7506. }
  7507. /**
  7508. * Create a new Observer with the specified callback
  7509. * @param callback the callback that will be executed for that Observer
  7510. * @param mask the mask used to filter observers
  7511. * @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.
  7512. * @param scope optional scope for the callback to be called from
  7513. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7514. * @returns the new observer created for the callback
  7515. */
  7516. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7517. if (mask === void 0) { mask = -1; }
  7518. if (insertFirst === void 0) { insertFirst = false; }
  7519. if (scope === void 0) { scope = null; }
  7520. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7521. if (!callback) {
  7522. return null;
  7523. }
  7524. var observer = new Observer(callback, mask, scope);
  7525. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7526. if (insertFirst) {
  7527. this._observers.unshift(observer);
  7528. }
  7529. else {
  7530. this._observers.push(observer);
  7531. }
  7532. if (this._onObserverAdded) {
  7533. this._onObserverAdded(observer);
  7534. }
  7535. return observer;
  7536. };
  7537. /**
  7538. * Remove an Observer from the Observable object
  7539. * @param observer the instance of the Observer to remove
  7540. * @returns false if it doesn't belong to this Observable
  7541. */
  7542. Observable.prototype.remove = function (observer) {
  7543. if (!observer) {
  7544. return false;
  7545. }
  7546. var index = this._observers.indexOf(observer);
  7547. if (index !== -1) {
  7548. this._observers.splice(index, 1);
  7549. return true;
  7550. }
  7551. return false;
  7552. };
  7553. /**
  7554. * Remove a callback from the Observable object
  7555. * @param callback the callback to remove
  7556. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7557. * @returns false if it doesn't belong to this Observable
  7558. */
  7559. Observable.prototype.removeCallback = function (callback, scope) {
  7560. for (var index = 0; index < this._observers.length; index++) {
  7561. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7562. this._observers.splice(index, 1);
  7563. return true;
  7564. }
  7565. }
  7566. return false;
  7567. };
  7568. Observable.prototype._deferUnregister = function (observer) {
  7569. var _this = this;
  7570. observer.unregisterOnNextCall = false;
  7571. observer._willBeUnregistered = true;
  7572. BABYLON.Tools.SetImmediate(function () {
  7573. _this.remove(observer);
  7574. });
  7575. };
  7576. /**
  7577. * Notify all Observers by calling their respective callback with the given data
  7578. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7579. * @param eventData defines the data to send to all observers
  7580. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7581. * @param target defines the original target of the state
  7582. * @param currentTarget defines the current target of the state
  7583. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7584. */
  7585. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7586. if (mask === void 0) { mask = -1; }
  7587. if (!this._observers.length) {
  7588. return true;
  7589. }
  7590. var state = this._eventState;
  7591. state.mask = mask;
  7592. state.target = target;
  7593. state.currentTarget = currentTarget;
  7594. state.skipNextObservers = false;
  7595. state.lastReturnValue = eventData;
  7596. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7597. var obs = _a[_i];
  7598. if (obs._willBeUnregistered) {
  7599. continue;
  7600. }
  7601. if (obs.mask & mask) {
  7602. if (obs.scope) {
  7603. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7604. }
  7605. else {
  7606. state.lastReturnValue = obs.callback(eventData, state);
  7607. }
  7608. if (obs.unregisterOnNextCall) {
  7609. this._deferUnregister(obs);
  7610. }
  7611. }
  7612. if (state.skipNextObservers) {
  7613. return false;
  7614. }
  7615. }
  7616. return true;
  7617. };
  7618. /**
  7619. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7620. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7621. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7622. * and it is crucial that all callbacks will be executed.
  7623. * The order of the callbacks is kept, callbacks are not executed parallel.
  7624. *
  7625. * @param eventData The data to be sent to each callback
  7626. * @param mask is used to filter observers defaults to -1
  7627. * @param target defines the callback target (see EventState)
  7628. * @param currentTarget defines he current object in the bubbling phase
  7629. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7630. */
  7631. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7632. var _this = this;
  7633. if (mask === void 0) { mask = -1; }
  7634. // create an empty promise
  7635. var p = Promise.resolve(eventData);
  7636. // no observers? return this promise.
  7637. if (!this._observers.length) {
  7638. return p;
  7639. }
  7640. var state = this._eventState;
  7641. state.mask = mask;
  7642. state.target = target;
  7643. state.currentTarget = currentTarget;
  7644. state.skipNextObservers = false;
  7645. // execute one callback after another (not using Promise.all, the order is important)
  7646. this._observers.forEach(function (obs) {
  7647. if (state.skipNextObservers) {
  7648. return;
  7649. }
  7650. if (obs._willBeUnregistered) {
  7651. return;
  7652. }
  7653. if (obs.mask & mask) {
  7654. if (obs.scope) {
  7655. p = p.then(function (lastReturnedValue) {
  7656. state.lastReturnValue = lastReturnedValue;
  7657. return obs.callback.apply(obs.scope, [eventData, state]);
  7658. });
  7659. }
  7660. else {
  7661. p = p.then(function (lastReturnedValue) {
  7662. state.lastReturnValue = lastReturnedValue;
  7663. return obs.callback(eventData, state);
  7664. });
  7665. }
  7666. if (obs.unregisterOnNextCall) {
  7667. _this._deferUnregister(obs);
  7668. }
  7669. }
  7670. });
  7671. // return the eventData
  7672. return p.then(function () { return eventData; });
  7673. };
  7674. /**
  7675. * Notify a specific observer
  7676. * @param observer defines the observer to notify
  7677. * @param eventData defines the data to be sent to each callback
  7678. * @param mask is used to filter observers defaults to -1
  7679. */
  7680. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7681. if (mask === void 0) { mask = -1; }
  7682. var state = this._eventState;
  7683. state.mask = mask;
  7684. state.skipNextObservers = false;
  7685. observer.callback(eventData, state);
  7686. };
  7687. /**
  7688. * Gets a boolean indicating if the observable has at least one observer
  7689. * @returns true is the Observable has at least one Observer registered
  7690. */
  7691. Observable.prototype.hasObservers = function () {
  7692. return this._observers.length > 0;
  7693. };
  7694. /**
  7695. * Clear the list of observers
  7696. */
  7697. Observable.prototype.clear = function () {
  7698. this._observers = new Array();
  7699. this._onObserverAdded = null;
  7700. };
  7701. /**
  7702. * Clone the current observable
  7703. * @returns a new observable
  7704. */
  7705. Observable.prototype.clone = function () {
  7706. var result = new Observable();
  7707. result._observers = this._observers.slice(0);
  7708. return result;
  7709. };
  7710. /**
  7711. * Does this observable handles observer registered with a given mask
  7712. * @param mask defines the mask to be tested
  7713. * @return whether or not one observer registered with the given mask is handeled
  7714. **/
  7715. Observable.prototype.hasSpecificMask = function (mask) {
  7716. if (mask === void 0) { mask = -1; }
  7717. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7718. var obs = _a[_i];
  7719. if (obs.mask & mask || obs.mask === mask) {
  7720. return true;
  7721. }
  7722. }
  7723. return false;
  7724. };
  7725. return Observable;
  7726. }());
  7727. BABYLON.Observable = Observable;
  7728. })(BABYLON || (BABYLON = {}));
  7729. //# sourceMappingURL=babylon.observable.js.map
  7730. "use strict";
  7731. var BABYLON;
  7732. (function (BABYLON) {
  7733. var SmartArray = /** @class */ (function () {
  7734. function SmartArray(capacity) {
  7735. this.length = 0;
  7736. this.data = new Array(capacity);
  7737. this._id = SmartArray._GlobalId++;
  7738. }
  7739. SmartArray.prototype.push = function (value) {
  7740. this.data[this.length++] = value;
  7741. if (this.length > this.data.length) {
  7742. this.data.length *= 2;
  7743. }
  7744. };
  7745. SmartArray.prototype.forEach = function (func) {
  7746. for (var index = 0; index < this.length; index++) {
  7747. func(this.data[index]);
  7748. }
  7749. };
  7750. SmartArray.prototype.sort = function (compareFn) {
  7751. this.data.sort(compareFn);
  7752. };
  7753. SmartArray.prototype.reset = function () {
  7754. this.length = 0;
  7755. };
  7756. SmartArray.prototype.dispose = function () {
  7757. this.reset();
  7758. if (this.data) {
  7759. this.data.length = 0;
  7760. this.data = [];
  7761. }
  7762. };
  7763. SmartArray.prototype.concat = function (array) {
  7764. if (array.length === 0) {
  7765. return;
  7766. }
  7767. if (this.length + array.length > this.data.length) {
  7768. this.data.length = (this.length + array.length) * 2;
  7769. }
  7770. for (var index = 0; index < array.length; index++) {
  7771. this.data[this.length++] = (array.data || array)[index];
  7772. }
  7773. };
  7774. SmartArray.prototype.indexOf = function (value) {
  7775. var position = this.data.indexOf(value);
  7776. if (position >= this.length) {
  7777. return -1;
  7778. }
  7779. return position;
  7780. };
  7781. SmartArray.prototype.contains = function (value) {
  7782. return this.data.indexOf(value) !== -1;
  7783. };
  7784. // Statics
  7785. SmartArray._GlobalId = 0;
  7786. return SmartArray;
  7787. }());
  7788. BABYLON.SmartArray = SmartArray;
  7789. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7790. __extends(SmartArrayNoDuplicate, _super);
  7791. function SmartArrayNoDuplicate() {
  7792. var _this = _super !== null && _super.apply(this, arguments) || this;
  7793. _this._duplicateId = 0;
  7794. return _this;
  7795. }
  7796. SmartArrayNoDuplicate.prototype.push = function (value) {
  7797. _super.prototype.push.call(this, value);
  7798. if (!value.__smartArrayFlags) {
  7799. value.__smartArrayFlags = {};
  7800. }
  7801. value.__smartArrayFlags[this._id] = this._duplicateId;
  7802. };
  7803. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7804. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7805. return false;
  7806. }
  7807. this.push(value);
  7808. return true;
  7809. };
  7810. SmartArrayNoDuplicate.prototype.reset = function () {
  7811. _super.prototype.reset.call(this);
  7812. this._duplicateId++;
  7813. };
  7814. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7815. if (array.length === 0) {
  7816. return;
  7817. }
  7818. if (this.length + array.length > this.data.length) {
  7819. this.data.length = (this.length + array.length) * 2;
  7820. }
  7821. for (var index = 0; index < array.length; index++) {
  7822. var item = (array.data || array)[index];
  7823. this.pushNoDuplicate(item);
  7824. }
  7825. };
  7826. return SmartArrayNoDuplicate;
  7827. }(SmartArray));
  7828. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7829. })(BABYLON || (BABYLON = {}));
  7830. //# sourceMappingURL=babylon.smartArray.js.map
  7831. "use strict";
  7832. var BABYLON;
  7833. (function (BABYLON) {
  7834. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7835. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7836. var LoadFileError = /** @class */ (function (_super) {
  7837. __extends(LoadFileError, _super);
  7838. function LoadFileError(message, request) {
  7839. var _this = _super.call(this, message) || this;
  7840. _this.request = request;
  7841. _this.name = "LoadFileError";
  7842. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7843. return _this;
  7844. }
  7845. // Polyfill for Object.setPrototypeOf if necessary.
  7846. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7847. return LoadFileError;
  7848. }(Error));
  7849. BABYLON.LoadFileError = LoadFileError;
  7850. var RetryStrategy = /** @class */ (function () {
  7851. function RetryStrategy() {
  7852. }
  7853. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7854. if (maxRetries === void 0) { maxRetries = 3; }
  7855. if (baseInterval === void 0) { baseInterval = 500; }
  7856. return function (url, request, retryIndex) {
  7857. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7858. return -1;
  7859. }
  7860. return Math.pow(2, retryIndex) * baseInterval;
  7861. };
  7862. };
  7863. return RetryStrategy;
  7864. }());
  7865. BABYLON.RetryStrategy = RetryStrategy;
  7866. // Screenshots
  7867. var screenshotCanvas;
  7868. var cloneValue = function (source, destinationObject) {
  7869. if (!source)
  7870. return null;
  7871. if (source instanceof BABYLON.Mesh) {
  7872. return null;
  7873. }
  7874. if (source instanceof BABYLON.SubMesh) {
  7875. return source.clone(destinationObject);
  7876. }
  7877. else if (source.clone) {
  7878. return source.clone();
  7879. }
  7880. return null;
  7881. };
  7882. var Tools = /** @class */ (function () {
  7883. function Tools() {
  7884. }
  7885. /**
  7886. * Interpolates between a and b via alpha
  7887. * @param a The lower value (returned when alpha = 0)
  7888. * @param b The upper value (returned when alpha = 1)
  7889. * @param alpha The interpolation-factor
  7890. * @return The mixed value
  7891. */
  7892. Tools.Mix = function (a, b, alpha) {
  7893. return a * (1 - alpha) + b * alpha;
  7894. };
  7895. Tools.Instantiate = function (className) {
  7896. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7897. return Tools.RegisteredExternalClasses[className];
  7898. }
  7899. var arr = className.split(".");
  7900. var fn = (window || this);
  7901. for (var i = 0, len = arr.length; i < len; i++) {
  7902. fn = fn[arr[i]];
  7903. }
  7904. if (typeof fn !== "function") {
  7905. return null;
  7906. }
  7907. return fn;
  7908. };
  7909. /**
  7910. * Provides a slice function that will work even on IE
  7911. * @param data defines the array to slice
  7912. * @param start defines the start of the data (optional)
  7913. * @param end defines the end of the data (optional)
  7914. * @returns the new sliced array
  7915. */
  7916. Tools.Slice = function (data, start, end) {
  7917. if (data.slice) {
  7918. return data.slice(start, end);
  7919. }
  7920. return Array.prototype.slice.call(data, start, end);
  7921. };
  7922. Tools.SetImmediate = function (action) {
  7923. if (window.setImmediate) {
  7924. window.setImmediate(action);
  7925. }
  7926. else {
  7927. setTimeout(action, 1);
  7928. }
  7929. };
  7930. Tools.IsExponentOfTwo = function (value) {
  7931. var count = 1;
  7932. do {
  7933. count *= 2;
  7934. } while (count < value);
  7935. return count === value;
  7936. };
  7937. /**
  7938. * Find the next highest power of two.
  7939. * @param x Number to start search from.
  7940. * @return Next highest power of two.
  7941. */
  7942. Tools.CeilingPOT = function (x) {
  7943. x--;
  7944. x |= x >> 1;
  7945. x |= x >> 2;
  7946. x |= x >> 4;
  7947. x |= x >> 8;
  7948. x |= x >> 16;
  7949. x++;
  7950. return x;
  7951. };
  7952. /**
  7953. * Find the next lowest power of two.
  7954. * @param x Number to start search from.
  7955. * @return Next lowest power of two.
  7956. */
  7957. Tools.FloorPOT = function (x) {
  7958. x = x | (x >> 1);
  7959. x = x | (x >> 2);
  7960. x = x | (x >> 4);
  7961. x = x | (x >> 8);
  7962. x = x | (x >> 16);
  7963. return x - (x >> 1);
  7964. };
  7965. /**
  7966. * Find the nearest power of two.
  7967. * @param x Number to start search from.
  7968. * @return Next nearest power of two.
  7969. */
  7970. Tools.NearestPOT = function (x) {
  7971. var c = Tools.CeilingPOT(x);
  7972. var f = Tools.FloorPOT(x);
  7973. return (c - x) > (x - f) ? f : c;
  7974. };
  7975. Tools.GetExponentOfTwo = function (value, max, mode) {
  7976. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7977. var pot;
  7978. switch (mode) {
  7979. case BABYLON.Engine.SCALEMODE_FLOOR:
  7980. pot = Tools.FloorPOT(value);
  7981. break;
  7982. case BABYLON.Engine.SCALEMODE_NEAREST:
  7983. pot = Tools.NearestPOT(value);
  7984. break;
  7985. case BABYLON.Engine.SCALEMODE_CEILING:
  7986. default:
  7987. pot = Tools.CeilingPOT(value);
  7988. break;
  7989. }
  7990. return Math.min(pot, max);
  7991. };
  7992. Tools.GetFilename = function (path) {
  7993. var index = path.lastIndexOf("/");
  7994. if (index < 0)
  7995. return path;
  7996. return path.substring(index + 1);
  7997. };
  7998. /**
  7999. * Extracts the "folder" part of a path (everything before the filename).
  8000. * @param uri The URI to extract the info from
  8001. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8002. * @returns The "folder" part of the path
  8003. */
  8004. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8005. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8006. var index = uri.lastIndexOf("/");
  8007. if (index < 0) {
  8008. if (returnUnchangedIfNoSlash) {
  8009. return uri;
  8010. }
  8011. return "";
  8012. }
  8013. return uri.substring(0, index + 1);
  8014. };
  8015. Tools.GetDOMTextContent = function (element) {
  8016. var result = "";
  8017. var child = element.firstChild;
  8018. while (child) {
  8019. if (child.nodeType === 3) {
  8020. result += child.textContent;
  8021. }
  8022. child = child.nextSibling;
  8023. }
  8024. return result;
  8025. };
  8026. Tools.ToDegrees = function (angle) {
  8027. return angle * 180 / Math.PI;
  8028. };
  8029. Tools.ToRadians = function (angle) {
  8030. return angle * Math.PI / 180;
  8031. };
  8032. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8033. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8034. var output = "";
  8035. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8036. var i = 0;
  8037. var bytes = new Uint8Array(buffer);
  8038. while (i < bytes.length) {
  8039. chr1 = bytes[i++];
  8040. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8041. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8042. enc1 = chr1 >> 2;
  8043. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8044. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8045. enc4 = chr3 & 63;
  8046. if (isNaN(chr2)) {
  8047. enc3 = enc4 = 64;
  8048. }
  8049. else if (isNaN(chr3)) {
  8050. enc4 = 64;
  8051. }
  8052. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8053. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8054. }
  8055. return "data:image/png;base64," + output;
  8056. };
  8057. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8058. if (bias === void 0) { bias = null; }
  8059. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8060. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8061. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8062. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8063. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8064. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8065. }
  8066. if (bias) {
  8067. minimum.x -= minimum.x * bias.x + bias.y;
  8068. minimum.y -= minimum.y * bias.x + bias.y;
  8069. minimum.z -= minimum.z * bias.x + bias.y;
  8070. maximum.x += maximum.x * bias.x + bias.y;
  8071. maximum.y += maximum.y * bias.x + bias.y;
  8072. maximum.z += maximum.z * bias.x + bias.y;
  8073. }
  8074. return {
  8075. minimum: minimum,
  8076. maximum: maximum
  8077. };
  8078. };
  8079. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8080. if (bias === void 0) { bias = null; }
  8081. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8082. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8083. if (!stride) {
  8084. stride = 3;
  8085. }
  8086. for (var index = start; index < start + count; index++) {
  8087. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8088. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8089. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8090. }
  8091. if (bias) {
  8092. minimum.x -= minimum.x * bias.x + bias.y;
  8093. minimum.y -= minimum.y * bias.x + bias.y;
  8094. minimum.z -= minimum.z * bias.x + bias.y;
  8095. maximum.x += maximum.x * bias.x + bias.y;
  8096. maximum.y += maximum.y * bias.x + bias.y;
  8097. maximum.z += maximum.z * bias.x + bias.y;
  8098. }
  8099. return {
  8100. minimum: minimum,
  8101. maximum: maximum
  8102. };
  8103. };
  8104. Tools.Vector2ArrayFeeder = function (array) {
  8105. return function (index) {
  8106. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8107. var length = isFloatArray ? array.length / 2 : array.length;
  8108. if (index >= length) {
  8109. return null;
  8110. }
  8111. if (isFloatArray) {
  8112. var fa = array;
  8113. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8114. }
  8115. var a = array;
  8116. return a[index];
  8117. };
  8118. };
  8119. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8120. if (bias === void 0) { bias = null; }
  8121. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8122. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8123. var i = 0;
  8124. var cur = feeder(i++);
  8125. while (cur) {
  8126. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8127. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8128. cur = feeder(i++);
  8129. }
  8130. if (bias) {
  8131. minimum.x -= minimum.x * bias.x + bias.y;
  8132. minimum.y -= minimum.y * bias.x + bias.y;
  8133. maximum.x += maximum.x * bias.x + bias.y;
  8134. maximum.y += maximum.y * bias.x + bias.y;
  8135. }
  8136. return {
  8137. minimum: minimum,
  8138. maximum: maximum
  8139. };
  8140. };
  8141. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8142. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8143. return null;
  8144. return Array.isArray(obj) ? obj : [obj];
  8145. };
  8146. // Misc.
  8147. Tools.GetPointerPrefix = function () {
  8148. var eventPrefix = "pointer";
  8149. // Check if pointer events are supported
  8150. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8151. eventPrefix = "mouse";
  8152. }
  8153. return eventPrefix;
  8154. };
  8155. /**
  8156. * @param func - the function to be called
  8157. * @param requester - the object that will request the next frame. Falls back to window.
  8158. */
  8159. Tools.QueueNewFrame = function (func, requester) {
  8160. if (!Tools.IsWindowObjectExist()) {
  8161. return setTimeout(func, 16);
  8162. }
  8163. if (!requester) {
  8164. requester = window;
  8165. }
  8166. if (requester.requestAnimationFrame) {
  8167. return requester.requestAnimationFrame(func);
  8168. }
  8169. else if (requester.msRequestAnimationFrame) {
  8170. return requester.msRequestAnimationFrame(func);
  8171. }
  8172. else if (requester.webkitRequestAnimationFrame) {
  8173. return requester.webkitRequestAnimationFrame(func);
  8174. }
  8175. else if (requester.mozRequestAnimationFrame) {
  8176. return requester.mozRequestAnimationFrame(func);
  8177. }
  8178. else if (requester.oRequestAnimationFrame) {
  8179. return requester.oRequestAnimationFrame(func);
  8180. }
  8181. else {
  8182. return window.setTimeout(func, 16);
  8183. }
  8184. };
  8185. Tools.RequestFullscreen = function (element) {
  8186. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8187. if (!requestFunction)
  8188. return;
  8189. requestFunction.call(element);
  8190. };
  8191. Tools.ExitFullscreen = function () {
  8192. if (document.exitFullscreen) {
  8193. document.exitFullscreen();
  8194. }
  8195. else if (document.mozCancelFullScreen) {
  8196. document.mozCancelFullScreen();
  8197. }
  8198. else if (document.webkitCancelFullScreen) {
  8199. document.webkitCancelFullScreen();
  8200. }
  8201. else if (document.msCancelFullScreen) {
  8202. document.msCancelFullScreen();
  8203. }
  8204. };
  8205. Tools.SetCorsBehavior = function (url, element) {
  8206. if (url && url.indexOf("data:") === 0) {
  8207. return;
  8208. }
  8209. if (Tools.CorsBehavior) {
  8210. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8211. element.crossOrigin = Tools.CorsBehavior;
  8212. }
  8213. else {
  8214. var result = Tools.CorsBehavior(url);
  8215. if (result) {
  8216. element.crossOrigin = result;
  8217. }
  8218. }
  8219. }
  8220. };
  8221. // External files
  8222. Tools.CleanUrl = function (url) {
  8223. url = url.replace(/#/mg, "%23");
  8224. return url;
  8225. };
  8226. Tools.LoadImage = function (url, onLoad, onError, database) {
  8227. if (url instanceof ArrayBuffer) {
  8228. url = Tools.EncodeArrayBufferTobase64(url);
  8229. }
  8230. url = Tools.CleanUrl(url);
  8231. url = Tools.PreprocessUrl(url);
  8232. var img = new Image();
  8233. Tools.SetCorsBehavior(url, img);
  8234. var loadHandler = function () {
  8235. img.removeEventListener("load", loadHandler);
  8236. img.removeEventListener("error", errorHandler);
  8237. onLoad(img);
  8238. };
  8239. var errorHandler = function (err) {
  8240. img.removeEventListener("load", loadHandler);
  8241. img.removeEventListener("error", errorHandler);
  8242. Tools.Error("Error while trying to load image: " + url);
  8243. if (onError) {
  8244. onError("Error while trying to load image: " + url, err);
  8245. }
  8246. };
  8247. img.addEventListener("load", loadHandler);
  8248. img.addEventListener("error", errorHandler);
  8249. var noIndexedDB = function () {
  8250. img.src = url;
  8251. };
  8252. var loadFromIndexedDB = function () {
  8253. if (database) {
  8254. database.loadImageFromDB(url, img);
  8255. }
  8256. };
  8257. //ANY database to do!
  8258. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8259. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8260. }
  8261. else {
  8262. if (url.indexOf("file:") !== -1) {
  8263. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8264. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8265. try {
  8266. var blobURL;
  8267. try {
  8268. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8269. }
  8270. catch (ex) {
  8271. // Chrome doesn't support oneTimeOnly parameter
  8272. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8273. }
  8274. img.src = blobURL;
  8275. }
  8276. catch (e) {
  8277. img.src = "";
  8278. }
  8279. return img;
  8280. }
  8281. }
  8282. noIndexedDB();
  8283. }
  8284. return img;
  8285. };
  8286. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8287. url = Tools.CleanUrl(url);
  8288. url = Tools.PreprocessUrl(url);
  8289. // If file and file input are set
  8290. if (url.indexOf("file:") !== -1) {
  8291. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8292. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8293. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8294. }
  8295. }
  8296. var loadUrl = Tools.BaseUrl + url;
  8297. var aborted = false;
  8298. var fileRequest = {
  8299. onCompleteObservable: new BABYLON.Observable(),
  8300. abort: function () { return aborted = true; },
  8301. };
  8302. var requestFile = function () {
  8303. var request = new XMLHttpRequest();
  8304. var retryHandle = null;
  8305. fileRequest.abort = function () {
  8306. aborted = true;
  8307. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8308. request.abort();
  8309. }
  8310. if (retryHandle !== null) {
  8311. clearTimeout(retryHandle);
  8312. retryHandle = null;
  8313. }
  8314. };
  8315. var retryLoop = function (retryIndex) {
  8316. request.open('GET', loadUrl, true);
  8317. if (useArrayBuffer) {
  8318. request.responseType = "arraybuffer";
  8319. }
  8320. if (onProgress) {
  8321. request.addEventListener("progress", onProgress);
  8322. }
  8323. var onLoadEnd = function () {
  8324. request.removeEventListener("loadend", onLoadEnd);
  8325. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8326. fileRequest.onCompleteObservable.clear();
  8327. };
  8328. request.addEventListener("loadend", onLoadEnd);
  8329. var onReadyStateChange = function () {
  8330. if (aborted) {
  8331. return;
  8332. }
  8333. // In case of undefined state in some browsers.
  8334. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8335. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8336. request.removeEventListener("readystatechange", onReadyStateChange);
  8337. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8338. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8339. return;
  8340. }
  8341. var retryStrategy = Tools.DefaultRetryStrategy;
  8342. if (retryStrategy) {
  8343. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8344. if (waitTime !== -1) {
  8345. // Prevent the request from completing for retry.
  8346. request.removeEventListener("loadend", onLoadEnd);
  8347. request = new XMLHttpRequest();
  8348. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8349. return;
  8350. }
  8351. }
  8352. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8353. if (onError) {
  8354. onError(request, e);
  8355. }
  8356. else {
  8357. throw e;
  8358. }
  8359. }
  8360. };
  8361. request.addEventListener("readystatechange", onReadyStateChange);
  8362. request.send();
  8363. };
  8364. retryLoop(0);
  8365. };
  8366. // Caching all files
  8367. if (database && database.enableSceneOffline) {
  8368. var noIndexedDB_1 = function () {
  8369. if (!aborted) {
  8370. requestFile();
  8371. }
  8372. };
  8373. var loadFromIndexedDB = function () {
  8374. // TODO: database needs to support aborting and should return a IFileRequest
  8375. if (aborted) {
  8376. return;
  8377. }
  8378. if (database) {
  8379. database.loadFileFromDB(url, function (data) {
  8380. if (!aborted) {
  8381. onSuccess(data);
  8382. }
  8383. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8384. }, onProgress ? function (event) {
  8385. if (!aborted) {
  8386. onProgress(event);
  8387. }
  8388. } : undefined, noIndexedDB_1, useArrayBuffer);
  8389. }
  8390. };
  8391. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8392. }
  8393. else {
  8394. requestFile();
  8395. }
  8396. return fileRequest;
  8397. };
  8398. /**
  8399. * Load a script (identified by an url). When the url returns, the
  8400. * content of this file is added into a new script element, attached to the DOM (body element)
  8401. */
  8402. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8403. var head = document.getElementsByTagName('head')[0];
  8404. var script = document.createElement('script');
  8405. script.type = 'text/javascript';
  8406. script.src = scriptUrl;
  8407. script.onload = function () {
  8408. if (onSuccess) {
  8409. onSuccess();
  8410. }
  8411. };
  8412. script.onerror = function (e) {
  8413. if (onError) {
  8414. onError("Unable to load script", e);
  8415. }
  8416. };
  8417. head.appendChild(script);
  8418. };
  8419. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8420. var reader = new FileReader();
  8421. var request = {
  8422. onCompleteObservable: new BABYLON.Observable(),
  8423. abort: function () { return reader.abort(); },
  8424. };
  8425. reader.onloadend = function (e) {
  8426. request.onCompleteObservable.notifyObservers(request);
  8427. };
  8428. reader.onload = function (e) {
  8429. //target doesn't have result from ts 1.3
  8430. callback(e.target['result']);
  8431. };
  8432. reader.onprogress = progressCallback;
  8433. reader.readAsDataURL(fileToLoad);
  8434. return request;
  8435. };
  8436. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8437. var reader = new FileReader();
  8438. var request = {
  8439. onCompleteObservable: new BABYLON.Observable(),
  8440. abort: function () { return reader.abort(); },
  8441. };
  8442. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8443. reader.onerror = function (e) {
  8444. Tools.Log("Error while reading file: " + fileToLoad.name);
  8445. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8446. };
  8447. reader.onload = function (e) {
  8448. //target doesn't have result from ts 1.3
  8449. callback(e.target['result']);
  8450. };
  8451. if (progressCallBack) {
  8452. reader.onprogress = progressCallBack;
  8453. }
  8454. if (!useArrayBuffer) {
  8455. // Asynchronous read
  8456. reader.readAsText(fileToLoad);
  8457. }
  8458. else {
  8459. reader.readAsArrayBuffer(fileToLoad);
  8460. }
  8461. return request;
  8462. };
  8463. //returns a downloadable url to a file content.
  8464. Tools.FileAsURL = function (content) {
  8465. var fileBlob = new Blob([content]);
  8466. var url = window.URL || window.webkitURL;
  8467. var link = url.createObjectURL(fileBlob);
  8468. return link;
  8469. };
  8470. // Misc.
  8471. Tools.Format = function (value, decimals) {
  8472. if (decimals === void 0) { decimals = 2; }
  8473. return value.toFixed(decimals);
  8474. };
  8475. Tools.CheckExtends = function (v, min, max) {
  8476. if (v.x < min.x)
  8477. min.x = v.x;
  8478. if (v.y < min.y)
  8479. min.y = v.y;
  8480. if (v.z < min.z)
  8481. min.z = v.z;
  8482. if (v.x > max.x)
  8483. max.x = v.x;
  8484. if (v.y > max.y)
  8485. max.y = v.y;
  8486. if (v.z > max.z)
  8487. max.z = v.z;
  8488. };
  8489. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8490. for (var prop in source) {
  8491. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8492. continue;
  8493. }
  8494. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8495. continue;
  8496. }
  8497. var sourceValue = source[prop];
  8498. var typeOfSourceValue = typeof sourceValue;
  8499. if (typeOfSourceValue === "function") {
  8500. continue;
  8501. }
  8502. try {
  8503. if (typeOfSourceValue === "object") {
  8504. if (sourceValue instanceof Array) {
  8505. destination[prop] = [];
  8506. if (sourceValue.length > 0) {
  8507. if (typeof sourceValue[0] == "object") {
  8508. for (var index = 0; index < sourceValue.length; index++) {
  8509. var clonedValue = cloneValue(sourceValue[index], destination);
  8510. if (destination[prop].indexOf(clonedValue) === -1) {
  8511. destination[prop].push(clonedValue);
  8512. }
  8513. }
  8514. }
  8515. else {
  8516. destination[prop] = sourceValue.slice(0);
  8517. }
  8518. }
  8519. }
  8520. else {
  8521. destination[prop] = cloneValue(sourceValue, destination);
  8522. }
  8523. }
  8524. else {
  8525. destination[prop] = sourceValue;
  8526. }
  8527. }
  8528. catch (e) {
  8529. // Just ignore error (it could be because of a read-only property)
  8530. }
  8531. }
  8532. };
  8533. Tools.IsEmpty = function (obj) {
  8534. for (var i in obj) {
  8535. if (obj.hasOwnProperty(i)) {
  8536. return false;
  8537. }
  8538. }
  8539. return true;
  8540. };
  8541. Tools.RegisterTopRootEvents = function (events) {
  8542. for (var index = 0; index < events.length; index++) {
  8543. var event = events[index];
  8544. window.addEventListener(event.name, event.handler, false);
  8545. try {
  8546. if (window.parent) {
  8547. window.parent.addEventListener(event.name, event.handler, false);
  8548. }
  8549. }
  8550. catch (e) {
  8551. // Silently fails...
  8552. }
  8553. }
  8554. };
  8555. Tools.UnregisterTopRootEvents = function (events) {
  8556. for (var index = 0; index < events.length; index++) {
  8557. var event = events[index];
  8558. window.removeEventListener(event.name, event.handler);
  8559. try {
  8560. if (window.parent) {
  8561. window.parent.removeEventListener(event.name, event.handler);
  8562. }
  8563. }
  8564. catch (e) {
  8565. // Silently fails...
  8566. }
  8567. }
  8568. };
  8569. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8570. if (mimeType === void 0) { mimeType = "image/png"; }
  8571. // Read the contents of the framebuffer
  8572. var numberOfChannelsByLine = width * 4;
  8573. var halfHeight = height / 2;
  8574. //Reading datas from WebGL
  8575. var data = engine.readPixels(0, 0, width, height);
  8576. //To flip image on Y axis.
  8577. for (var i = 0; i < halfHeight; i++) {
  8578. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8579. var currentCell = j + i * numberOfChannelsByLine;
  8580. var targetLine = height - i - 1;
  8581. var targetCell = j + targetLine * numberOfChannelsByLine;
  8582. var temp = data[currentCell];
  8583. data[currentCell] = data[targetCell];
  8584. data[targetCell] = temp;
  8585. }
  8586. }
  8587. // Create a 2D canvas to store the result
  8588. if (!screenshotCanvas) {
  8589. screenshotCanvas = document.createElement('canvas');
  8590. }
  8591. screenshotCanvas.width = width;
  8592. screenshotCanvas.height = height;
  8593. var context = screenshotCanvas.getContext('2d');
  8594. if (context) {
  8595. // Copy the pixels to a 2D canvas
  8596. var imageData = context.createImageData(width, height);
  8597. var castData = (imageData.data);
  8598. castData.set(data);
  8599. context.putImageData(imageData, 0, 0);
  8600. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8601. }
  8602. };
  8603. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8604. if (mimeType === void 0) { mimeType = "image/png"; }
  8605. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8606. if (successCallback) {
  8607. successCallback(base64Image);
  8608. }
  8609. else {
  8610. // We need HTMLCanvasElement.toBlob for HD screenshots
  8611. if (!screenshotCanvas.toBlob) {
  8612. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8613. screenshotCanvas.toBlob = function (callback, type, quality) {
  8614. var _this = this;
  8615. setTimeout(function () {
  8616. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8617. for (var i = 0; i < len; i++) {
  8618. arr[i] = binStr.charCodeAt(i);
  8619. }
  8620. callback(new Blob([arr], { type: type || 'image/png' }));
  8621. });
  8622. };
  8623. }
  8624. screenshotCanvas.toBlob(function (blob) {
  8625. var url = URL.createObjectURL(blob);
  8626. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8627. if (("download" in document.createElement("a"))) {
  8628. var a = window.document.createElement("a");
  8629. a.href = url;
  8630. if (fileName) {
  8631. a.setAttribute("download", fileName);
  8632. }
  8633. else {
  8634. var date = new Date();
  8635. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8636. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8637. }
  8638. window.document.body.appendChild(a);
  8639. a.addEventListener("click", function () {
  8640. if (a.parentElement) {
  8641. a.parentElement.removeChild(a);
  8642. }
  8643. });
  8644. a.click();
  8645. }
  8646. else {
  8647. var newWindow = window.open("");
  8648. if (!newWindow)
  8649. return;
  8650. var img = newWindow.document.createElement("img");
  8651. img.onload = function () {
  8652. // no longer need to read the blob so it's revoked
  8653. URL.revokeObjectURL(url);
  8654. };
  8655. img.src = url;
  8656. newWindow.document.body.appendChild(img);
  8657. }
  8658. });
  8659. }
  8660. };
  8661. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8662. if (mimeType === void 0) { mimeType = "image/png"; }
  8663. var width;
  8664. var height;
  8665. // If a precision value is specified
  8666. if (size.precision) {
  8667. width = Math.round(engine.getRenderWidth() * size.precision);
  8668. height = Math.round(width / engine.getAspectRatio(camera));
  8669. }
  8670. else if (size.width && size.height) {
  8671. width = size.width;
  8672. height = size.height;
  8673. }
  8674. else if (size.width && !size.height) {
  8675. width = size.width;
  8676. height = Math.round(width / engine.getAspectRatio(camera));
  8677. }
  8678. else if (size.height && !size.width) {
  8679. height = size.height;
  8680. width = Math.round(height * engine.getAspectRatio(camera));
  8681. }
  8682. else if (!isNaN(size)) {
  8683. height = size;
  8684. width = size;
  8685. }
  8686. else {
  8687. Tools.Error("Invalid 'size' parameter !");
  8688. return;
  8689. }
  8690. if (!screenshotCanvas) {
  8691. screenshotCanvas = document.createElement('canvas');
  8692. }
  8693. screenshotCanvas.width = width;
  8694. screenshotCanvas.height = height;
  8695. var renderContext = screenshotCanvas.getContext("2d");
  8696. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8697. var newWidth = width;
  8698. var newHeight = newWidth / ratio;
  8699. if (newHeight > height) {
  8700. newHeight = height;
  8701. newWidth = newHeight * ratio;
  8702. }
  8703. var offsetX = Math.max(0, width - newWidth) / 2;
  8704. var offsetY = Math.max(0, height - newHeight) / 2;
  8705. var renderingCanvas = engine.getRenderingCanvas();
  8706. if (renderContext && renderingCanvas) {
  8707. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8708. }
  8709. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8710. };
  8711. /**
  8712. * Generates an image screenshot from the specified camera.
  8713. *
  8714. * @param engine The engine to use for rendering
  8715. * @param camera The camera to use for rendering
  8716. * @param size This parameter can be set to a single number or to an object with the
  8717. * following (optional) properties: precision, width, height. If a single number is passed,
  8718. * it will be used for both width and height. If an object is passed, the screenshot size
  8719. * will be derived from the parameters. The precision property is a multiplier allowing
  8720. * rendering at a higher or lower resolution.
  8721. * @param successCallback The callback receives a single parameter which contains the
  8722. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8723. * src parameter of an <img> to display it.
  8724. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8725. * Check your browser for supported MIME types.
  8726. * @param samples Texture samples (default: 1)
  8727. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8728. * @param fileName A name for for the downloaded file.
  8729. * @constructor
  8730. */
  8731. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8732. if (mimeType === void 0) { mimeType = "image/png"; }
  8733. if (samples === void 0) { samples = 1; }
  8734. if (antialiasing === void 0) { antialiasing = false; }
  8735. var width;
  8736. var height;
  8737. //If a precision value is specified
  8738. if (size.precision) {
  8739. width = Math.round(engine.getRenderWidth() * size.precision);
  8740. height = Math.round(width / engine.getAspectRatio(camera));
  8741. size = { width: width, height: height };
  8742. }
  8743. else if (size.width && size.height) {
  8744. width = size.width;
  8745. height = size.height;
  8746. }
  8747. else if (size.width && !size.height) {
  8748. width = size.width;
  8749. height = Math.round(width / engine.getAspectRatio(camera));
  8750. size = { width: width, height: height };
  8751. }
  8752. else if (size.height && !size.width) {
  8753. height = size.height;
  8754. width = Math.round(height * engine.getAspectRatio(camera));
  8755. size = { width: width, height: height };
  8756. }
  8757. else if (!isNaN(size)) {
  8758. height = size;
  8759. width = size;
  8760. }
  8761. else {
  8762. Tools.Error("Invalid 'size' parameter !");
  8763. return;
  8764. }
  8765. var scene = camera.getScene();
  8766. var previousCamera = null;
  8767. if (scene.activeCamera !== camera) {
  8768. previousCamera = scene.activeCamera;
  8769. scene.activeCamera = camera;
  8770. }
  8771. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8772. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8773. texture.renderList = null;
  8774. texture.samples = samples;
  8775. if (antialiasing) {
  8776. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8777. }
  8778. texture.onAfterRenderObservable.add(function () {
  8779. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8780. });
  8781. scene.incrementRenderId();
  8782. scene.resetCachedMaterial();
  8783. texture.render(true);
  8784. texture.dispose();
  8785. if (previousCamera) {
  8786. scene.activeCamera = previousCamera;
  8787. }
  8788. camera.getProjectionMatrix(true); // Force cache refresh;
  8789. };
  8790. // XHR response validator for local file scenario
  8791. Tools.ValidateXHRData = function (xhr, dataType) {
  8792. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8793. if (dataType === void 0) { dataType = 7; }
  8794. try {
  8795. if (dataType & 1) {
  8796. if (xhr.responseText && xhr.responseText.length > 0) {
  8797. return true;
  8798. }
  8799. else if (dataType === 1) {
  8800. return false;
  8801. }
  8802. }
  8803. if (dataType & 2) {
  8804. // Check header width and height since there is no "TGA" magic number
  8805. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8806. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8807. return true;
  8808. }
  8809. else if (dataType === 2) {
  8810. return false;
  8811. }
  8812. }
  8813. if (dataType & 4) {
  8814. // Check for the "DDS" magic number
  8815. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8816. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8817. return true;
  8818. }
  8819. else {
  8820. return false;
  8821. }
  8822. }
  8823. }
  8824. catch (e) {
  8825. // Global protection
  8826. }
  8827. return false;
  8828. };
  8829. /**
  8830. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8831. * Be aware Math.random() could cause collisions, but:
  8832. * "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"
  8833. */
  8834. Tools.RandomId = function () {
  8835. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8836. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8837. return v.toString(16);
  8838. });
  8839. };
  8840. /**
  8841. * Test if the given uri is a base64 string.
  8842. * @param uri The uri to test
  8843. * @return True if the uri is a base64 string or false otherwise.
  8844. */
  8845. Tools.IsBase64 = function (uri) {
  8846. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8847. };
  8848. /**
  8849. * Decode the given base64 uri.
  8850. * @param uri The uri to decode
  8851. * @return The decoded base64 data.
  8852. */
  8853. Tools.DecodeBase64 = function (uri) {
  8854. var decodedString = atob(uri.split(",")[1]);
  8855. var bufferLength = decodedString.length;
  8856. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8857. for (var i = 0; i < bufferLength; i++) {
  8858. bufferView[i] = decodedString.charCodeAt(i);
  8859. }
  8860. return bufferView.buffer;
  8861. };
  8862. Object.defineProperty(Tools, "NoneLogLevel", {
  8863. get: function () {
  8864. return Tools._NoneLogLevel;
  8865. },
  8866. enumerable: true,
  8867. configurable: true
  8868. });
  8869. Object.defineProperty(Tools, "MessageLogLevel", {
  8870. get: function () {
  8871. return Tools._MessageLogLevel;
  8872. },
  8873. enumerable: true,
  8874. configurable: true
  8875. });
  8876. Object.defineProperty(Tools, "WarningLogLevel", {
  8877. get: function () {
  8878. return Tools._WarningLogLevel;
  8879. },
  8880. enumerable: true,
  8881. configurable: true
  8882. });
  8883. Object.defineProperty(Tools, "ErrorLogLevel", {
  8884. get: function () {
  8885. return Tools._ErrorLogLevel;
  8886. },
  8887. enumerable: true,
  8888. configurable: true
  8889. });
  8890. Object.defineProperty(Tools, "AllLogLevel", {
  8891. get: function () {
  8892. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8893. },
  8894. enumerable: true,
  8895. configurable: true
  8896. });
  8897. Tools._AddLogEntry = function (entry) {
  8898. Tools._LogCache = entry + Tools._LogCache;
  8899. if (Tools.OnNewCacheEntry) {
  8900. Tools.OnNewCacheEntry(entry);
  8901. }
  8902. };
  8903. Tools._FormatMessage = function (message) {
  8904. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8905. var date = new Date();
  8906. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8907. };
  8908. Tools._LogDisabled = function (message) {
  8909. // nothing to do
  8910. };
  8911. Tools._LogEnabled = function (message) {
  8912. var formattedMessage = Tools._FormatMessage(message);
  8913. console.log("BJS - " + formattedMessage);
  8914. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8915. Tools._AddLogEntry(entry);
  8916. };
  8917. Tools._WarnDisabled = function (message) {
  8918. // nothing to do
  8919. };
  8920. Tools._WarnEnabled = function (message) {
  8921. var formattedMessage = Tools._FormatMessage(message);
  8922. console.warn("BJS - " + formattedMessage);
  8923. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8924. Tools._AddLogEntry(entry);
  8925. };
  8926. Tools._ErrorDisabled = function (message) {
  8927. // nothing to do
  8928. };
  8929. Tools._ErrorEnabled = function (message) {
  8930. Tools.errorsCount++;
  8931. var formattedMessage = Tools._FormatMessage(message);
  8932. console.error("BJS - " + formattedMessage);
  8933. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8934. Tools._AddLogEntry(entry);
  8935. };
  8936. Object.defineProperty(Tools, "LogCache", {
  8937. get: function () {
  8938. return Tools._LogCache;
  8939. },
  8940. enumerable: true,
  8941. configurable: true
  8942. });
  8943. Tools.ClearLogCache = function () {
  8944. Tools._LogCache = "";
  8945. Tools.errorsCount = 0;
  8946. };
  8947. Object.defineProperty(Tools, "LogLevels", {
  8948. set: function (level) {
  8949. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8950. Tools.Log = Tools._LogEnabled;
  8951. }
  8952. else {
  8953. Tools.Log = Tools._LogDisabled;
  8954. }
  8955. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8956. Tools.Warn = Tools._WarnEnabled;
  8957. }
  8958. else {
  8959. Tools.Warn = Tools._WarnDisabled;
  8960. }
  8961. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8962. Tools.Error = Tools._ErrorEnabled;
  8963. }
  8964. else {
  8965. Tools.Error = Tools._ErrorDisabled;
  8966. }
  8967. },
  8968. enumerable: true,
  8969. configurable: true
  8970. });
  8971. Tools.IsWindowObjectExist = function () {
  8972. return (typeof window) !== "undefined";
  8973. };
  8974. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8975. get: function () {
  8976. return Tools._PerformanceNoneLogLevel;
  8977. },
  8978. enumerable: true,
  8979. configurable: true
  8980. });
  8981. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8982. get: function () {
  8983. return Tools._PerformanceUserMarkLogLevel;
  8984. },
  8985. enumerable: true,
  8986. configurable: true
  8987. });
  8988. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8989. get: function () {
  8990. return Tools._PerformanceConsoleLogLevel;
  8991. },
  8992. enumerable: true,
  8993. configurable: true
  8994. });
  8995. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8996. set: function (level) {
  8997. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8998. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8999. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9000. return;
  9001. }
  9002. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9003. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9004. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9005. return;
  9006. }
  9007. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9008. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9009. },
  9010. enumerable: true,
  9011. configurable: true
  9012. });
  9013. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9014. };
  9015. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9016. };
  9017. Tools._StartUserMark = function (counterName, condition) {
  9018. if (condition === void 0) { condition = true; }
  9019. if (!Tools._performance) {
  9020. if (!Tools.IsWindowObjectExist()) {
  9021. return;
  9022. }
  9023. Tools._performance = window.performance;
  9024. }
  9025. if (!condition || !Tools._performance.mark) {
  9026. return;
  9027. }
  9028. Tools._performance.mark(counterName + "-Begin");
  9029. };
  9030. Tools._EndUserMark = function (counterName, condition) {
  9031. if (condition === void 0) { condition = true; }
  9032. if (!condition || !Tools._performance.mark) {
  9033. return;
  9034. }
  9035. Tools._performance.mark(counterName + "-End");
  9036. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9037. };
  9038. Tools._StartPerformanceConsole = function (counterName, condition) {
  9039. if (condition === void 0) { condition = true; }
  9040. if (!condition) {
  9041. return;
  9042. }
  9043. Tools._StartUserMark(counterName, condition);
  9044. if (console.time) {
  9045. console.time(counterName);
  9046. }
  9047. };
  9048. Tools._EndPerformanceConsole = function (counterName, condition) {
  9049. if (condition === void 0) { condition = true; }
  9050. if (!condition) {
  9051. return;
  9052. }
  9053. Tools._EndUserMark(counterName, condition);
  9054. if (console.time) {
  9055. console.timeEnd(counterName);
  9056. }
  9057. };
  9058. Object.defineProperty(Tools, "Now", {
  9059. get: function () {
  9060. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9061. return window.performance.now();
  9062. }
  9063. return new Date().getTime();
  9064. },
  9065. enumerable: true,
  9066. configurable: true
  9067. });
  9068. /**
  9069. * This method will return the name of the class used to create the instance of the given object.
  9070. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9071. * @param object the object to get the class name from
  9072. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9073. */
  9074. Tools.GetClassName = function (object, isType) {
  9075. if (isType === void 0) { isType = false; }
  9076. var name = null;
  9077. if (!isType && object.getClassName) {
  9078. name = object.getClassName();
  9079. }
  9080. else {
  9081. if (object instanceof Object) {
  9082. var classObj = isType ? object : Object.getPrototypeOf(object);
  9083. name = classObj.constructor["__bjsclassName__"];
  9084. }
  9085. if (!name) {
  9086. name = typeof object;
  9087. }
  9088. }
  9089. return name;
  9090. };
  9091. Tools.First = function (array, predicate) {
  9092. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9093. var el = array_1[_i];
  9094. if (predicate(el)) {
  9095. return el;
  9096. }
  9097. }
  9098. return null;
  9099. };
  9100. /**
  9101. * This method will return the name of the full name of the class, including its owning module (if any).
  9102. * 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).
  9103. * @param object the object to get the class name from
  9104. * @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.
  9105. */
  9106. Tools.getFullClassName = function (object, isType) {
  9107. if (isType === void 0) { isType = false; }
  9108. var className = null;
  9109. var moduleName = null;
  9110. if (!isType && object.getClassName) {
  9111. className = object.getClassName();
  9112. }
  9113. else {
  9114. if (object instanceof Object) {
  9115. var classObj = isType ? object : Object.getPrototypeOf(object);
  9116. className = classObj.constructor["__bjsclassName__"];
  9117. moduleName = classObj.constructor["__bjsmoduleName__"];
  9118. }
  9119. if (!className) {
  9120. className = typeof object;
  9121. }
  9122. }
  9123. if (!className) {
  9124. return null;
  9125. }
  9126. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9127. };
  9128. /**
  9129. * 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.
  9130. * @param array
  9131. */
  9132. Tools.arrayOrStringFeeder = function (array) {
  9133. return function (index) {
  9134. if (index >= array.length) {
  9135. return null;
  9136. }
  9137. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9138. if (val && val.getHashCode) {
  9139. val = val.getHashCode();
  9140. }
  9141. if (typeof val === "string") {
  9142. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9143. }
  9144. return val;
  9145. };
  9146. };
  9147. /**
  9148. * Compute the hashCode of a stream of number
  9149. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9150. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9151. * @return the hash code computed
  9152. */
  9153. Tools.hashCodeFromStream = function (feeder) {
  9154. // Based from here: http://stackoverflow.com/a/7616484/802124
  9155. var hash = 0;
  9156. var index = 0;
  9157. var chr = feeder(index++);
  9158. while (chr != null) {
  9159. hash = ((hash << 5) - hash) + chr;
  9160. hash |= 0; // Convert to 32bit integer
  9161. chr = feeder(index++);
  9162. }
  9163. return hash;
  9164. };
  9165. /**
  9166. * Returns a promise that resolves after the given amount of time.
  9167. * @param delay Number of milliseconds to delay
  9168. * @returns Promise that resolves after the given amount of time
  9169. */
  9170. Tools.DelayAsync = function (delay) {
  9171. return new Promise(function (resolve) {
  9172. setTimeout(function () {
  9173. resolve();
  9174. }, delay);
  9175. });
  9176. };
  9177. Tools.BaseUrl = "";
  9178. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9179. /**
  9180. * Default behaviour for cors in the application.
  9181. * It can be a string if the expected behavior is identical in the entire app.
  9182. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9183. */
  9184. Tools.CorsBehavior = "anonymous";
  9185. Tools.UseFallbackTexture = true;
  9186. /**
  9187. * Use this object to register external classes like custom textures or material
  9188. * to allow the laoders to instantiate them
  9189. */
  9190. Tools.RegisteredExternalClasses = {};
  9191. // Used in case of a texture loading problem
  9192. 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";
  9193. Tools.PreprocessUrl = function (url) {
  9194. return url;
  9195. };
  9196. // Logs
  9197. Tools._NoneLogLevel = 0;
  9198. Tools._MessageLogLevel = 1;
  9199. Tools._WarningLogLevel = 2;
  9200. Tools._ErrorLogLevel = 4;
  9201. Tools._LogCache = "";
  9202. Tools.errorsCount = 0;
  9203. Tools.Log = Tools._LogEnabled;
  9204. Tools.Warn = Tools._WarnEnabled;
  9205. Tools.Error = Tools._ErrorEnabled;
  9206. // Performances
  9207. Tools._PerformanceNoneLogLevel = 0;
  9208. Tools._PerformanceUserMarkLogLevel = 1;
  9209. Tools._PerformanceConsoleLogLevel = 2;
  9210. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9211. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9212. return Tools;
  9213. }());
  9214. BABYLON.Tools = Tools;
  9215. /**
  9216. * This class is used to track a performance counter which is number based.
  9217. * The user has access to many properties which give statistics of different nature
  9218. *
  9219. * The implementer can track two kinds of Performance Counter: time and count
  9220. * 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.
  9221. * 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.
  9222. */
  9223. var PerfCounter = /** @class */ (function () {
  9224. function PerfCounter() {
  9225. this._startMonitoringTime = 0;
  9226. this._min = 0;
  9227. this._max = 0;
  9228. this._average = 0;
  9229. this._lastSecAverage = 0;
  9230. this._current = 0;
  9231. this._totalValueCount = 0;
  9232. this._totalAccumulated = 0;
  9233. this._lastSecAccumulated = 0;
  9234. this._lastSecTime = 0;
  9235. this._lastSecValueCount = 0;
  9236. }
  9237. Object.defineProperty(PerfCounter.prototype, "min", {
  9238. /**
  9239. * Returns the smallest value ever
  9240. */
  9241. get: function () {
  9242. return this._min;
  9243. },
  9244. enumerable: true,
  9245. configurable: true
  9246. });
  9247. Object.defineProperty(PerfCounter.prototype, "max", {
  9248. /**
  9249. * Returns the biggest value ever
  9250. */
  9251. get: function () {
  9252. return this._max;
  9253. },
  9254. enumerable: true,
  9255. configurable: true
  9256. });
  9257. Object.defineProperty(PerfCounter.prototype, "average", {
  9258. /**
  9259. * Returns the average value since the performance counter is running
  9260. */
  9261. get: function () {
  9262. return this._average;
  9263. },
  9264. enumerable: true,
  9265. configurable: true
  9266. });
  9267. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9268. /**
  9269. * Returns the average value of the last second the counter was monitored
  9270. */
  9271. get: function () {
  9272. return this._lastSecAverage;
  9273. },
  9274. enumerable: true,
  9275. configurable: true
  9276. });
  9277. Object.defineProperty(PerfCounter.prototype, "current", {
  9278. /**
  9279. * Returns the current value
  9280. */
  9281. get: function () {
  9282. return this._current;
  9283. },
  9284. enumerable: true,
  9285. configurable: true
  9286. });
  9287. Object.defineProperty(PerfCounter.prototype, "total", {
  9288. get: function () {
  9289. return this._totalAccumulated;
  9290. },
  9291. enumerable: true,
  9292. configurable: true
  9293. });
  9294. Object.defineProperty(PerfCounter.prototype, "count", {
  9295. get: function () {
  9296. return this._totalValueCount;
  9297. },
  9298. enumerable: true,
  9299. configurable: true
  9300. });
  9301. /**
  9302. * Call this method to start monitoring a new frame.
  9303. * 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.
  9304. */
  9305. PerfCounter.prototype.fetchNewFrame = function () {
  9306. this._totalValueCount++;
  9307. this._current = 0;
  9308. this._lastSecValueCount++;
  9309. };
  9310. /**
  9311. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9312. * @param newCount the count value to add to the monitored count
  9313. * @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.
  9314. */
  9315. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9316. if (!PerfCounter.Enabled) {
  9317. return;
  9318. }
  9319. this._current += newCount;
  9320. if (fetchResult) {
  9321. this._fetchResult();
  9322. }
  9323. };
  9324. /**
  9325. * Start monitoring this performance counter
  9326. */
  9327. PerfCounter.prototype.beginMonitoring = function () {
  9328. if (!PerfCounter.Enabled) {
  9329. return;
  9330. }
  9331. this._startMonitoringTime = Tools.Now;
  9332. };
  9333. /**
  9334. * Compute the time lapsed since the previous beginMonitoring() call.
  9335. * @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
  9336. */
  9337. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9338. if (newFrame === void 0) { newFrame = true; }
  9339. if (!PerfCounter.Enabled) {
  9340. return;
  9341. }
  9342. if (newFrame) {
  9343. this.fetchNewFrame();
  9344. }
  9345. var currentTime = Tools.Now;
  9346. this._current = currentTime - this._startMonitoringTime;
  9347. if (newFrame) {
  9348. this._fetchResult();
  9349. }
  9350. };
  9351. PerfCounter.prototype._fetchResult = function () {
  9352. this._totalAccumulated += this._current;
  9353. this._lastSecAccumulated += this._current;
  9354. // Min/Max update
  9355. this._min = Math.min(this._min, this._current);
  9356. this._max = Math.max(this._max, this._current);
  9357. this._average = this._totalAccumulated / this._totalValueCount;
  9358. // Reset last sec?
  9359. var now = Tools.Now;
  9360. if ((now - this._lastSecTime) > 1000) {
  9361. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9362. this._lastSecTime = now;
  9363. this._lastSecAccumulated = 0;
  9364. this._lastSecValueCount = 0;
  9365. }
  9366. };
  9367. PerfCounter.Enabled = true;
  9368. return PerfCounter;
  9369. }());
  9370. BABYLON.PerfCounter = PerfCounter;
  9371. /**
  9372. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9373. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9374. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9375. * @param name The name of the class, case should be preserved
  9376. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9377. */
  9378. function className(name, module) {
  9379. return function (target) {
  9380. target["__bjsclassName__"] = name;
  9381. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9382. };
  9383. }
  9384. BABYLON.className = className;
  9385. /**
  9386. * An implementation of a loop for asynchronous functions.
  9387. */
  9388. var AsyncLoop = /** @class */ (function () {
  9389. /**
  9390. * Constroctor.
  9391. * @param iterations the number of iterations.
  9392. * @param _fn the function to run each iteration
  9393. * @param _successCallback the callback that will be called upon succesful execution
  9394. * @param offset starting offset.
  9395. */
  9396. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9397. if (offset === void 0) { offset = 0; }
  9398. this.iterations = iterations;
  9399. this._fn = _fn;
  9400. this._successCallback = _successCallback;
  9401. this.index = offset - 1;
  9402. this._done = false;
  9403. }
  9404. /**
  9405. * Execute the next iteration. Must be called after the last iteration was finished.
  9406. */
  9407. AsyncLoop.prototype.executeNext = function () {
  9408. if (!this._done) {
  9409. if (this.index + 1 < this.iterations) {
  9410. ++this.index;
  9411. this._fn(this);
  9412. }
  9413. else {
  9414. this.breakLoop();
  9415. }
  9416. }
  9417. };
  9418. /**
  9419. * Break the loop and run the success callback.
  9420. */
  9421. AsyncLoop.prototype.breakLoop = function () {
  9422. this._done = true;
  9423. this._successCallback();
  9424. };
  9425. /**
  9426. * Helper function
  9427. */
  9428. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9429. if (offset === void 0) { offset = 0; }
  9430. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9431. loop.executeNext();
  9432. return loop;
  9433. };
  9434. /**
  9435. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9436. * @param iterations total number of iterations
  9437. * @param syncedIterations number of synchronous iterations in each async iteration.
  9438. * @param fn the function to call each iteration.
  9439. * @param callback a success call back that will be called when iterating stops.
  9440. * @param breakFunction a break condition (optional)
  9441. * @param timeout timeout settings for the setTimeout function. default - 0.
  9442. * @constructor
  9443. */
  9444. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9445. if (timeout === void 0) { timeout = 0; }
  9446. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9447. if (breakFunction && breakFunction())
  9448. loop.breakLoop();
  9449. else {
  9450. setTimeout(function () {
  9451. for (var i = 0; i < syncedIterations; ++i) {
  9452. var iteration = (loop.index * syncedIterations) + i;
  9453. if (iteration >= iterations)
  9454. break;
  9455. fn(iteration);
  9456. if (breakFunction && breakFunction()) {
  9457. loop.breakLoop();
  9458. break;
  9459. }
  9460. }
  9461. loop.executeNext();
  9462. }, timeout);
  9463. }
  9464. }, callback);
  9465. };
  9466. return AsyncLoop;
  9467. }());
  9468. BABYLON.AsyncLoop = AsyncLoop;
  9469. })(BABYLON || (BABYLON = {}));
  9470. //# sourceMappingURL=babylon.tools.js.map
  9471. "use strict";
  9472. var BABYLON;
  9473. (function (BABYLON) {
  9474. var PromiseStates;
  9475. (function (PromiseStates) {
  9476. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9477. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9478. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9479. })(PromiseStates || (PromiseStates = {}));
  9480. var FulFillmentAgregator = /** @class */ (function () {
  9481. function FulFillmentAgregator() {
  9482. this.count = 0;
  9483. this.target = 0;
  9484. this.results = [];
  9485. }
  9486. return FulFillmentAgregator;
  9487. }());
  9488. var InternalPromise = /** @class */ (function () {
  9489. function InternalPromise(resolver) {
  9490. var _this = this;
  9491. this._state = PromiseStates.Pending;
  9492. this._children = new Array();
  9493. this._rejectWasConsumed = false;
  9494. if (!resolver) {
  9495. return;
  9496. }
  9497. try {
  9498. resolver(function (value) {
  9499. _this._resolve(value);
  9500. }, function (reason) {
  9501. _this._reject(reason);
  9502. });
  9503. }
  9504. catch (e) {
  9505. this._reject(e);
  9506. }
  9507. }
  9508. InternalPromise.prototype.catch = function (onRejected) {
  9509. return this.then(undefined, onRejected);
  9510. };
  9511. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9512. var _this = this;
  9513. var newPromise = new InternalPromise();
  9514. newPromise._onFulfilled = onFulfilled;
  9515. newPromise._onRejected = onRejected;
  9516. // Composition
  9517. this._children.push(newPromise);
  9518. if (this._state !== PromiseStates.Pending) {
  9519. BABYLON.Tools.SetImmediate(function () {
  9520. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9521. var returnedValue = newPromise._resolve(_this._result);
  9522. if (returnedValue !== undefined && returnedValue !== null) {
  9523. if (returnedValue._state !== undefined) {
  9524. var returnedPromise = returnedValue;
  9525. newPromise._children.push(returnedPromise);
  9526. newPromise = returnedPromise;
  9527. }
  9528. else {
  9529. newPromise._result = returnedValue;
  9530. }
  9531. }
  9532. }
  9533. else {
  9534. newPromise._reject(_this._reason);
  9535. }
  9536. });
  9537. }
  9538. return newPromise;
  9539. };
  9540. InternalPromise.prototype._moveChildren = function (children) {
  9541. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9542. if (this._state === PromiseStates.Fulfilled) {
  9543. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9544. var child = _b[_i];
  9545. child._resolve(this._result);
  9546. }
  9547. }
  9548. else if (this._state === PromiseStates.Rejected) {
  9549. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9550. var child = _d[_c];
  9551. child._reject(this._reason);
  9552. }
  9553. }
  9554. var _a;
  9555. };
  9556. InternalPromise.prototype._resolve = function (value) {
  9557. try {
  9558. this._state = PromiseStates.Fulfilled;
  9559. var returnedValue = null;
  9560. if (this._onFulfilled) {
  9561. returnedValue = this._onFulfilled(value);
  9562. }
  9563. if (returnedValue !== undefined && returnedValue !== null) {
  9564. if (returnedValue._state !== undefined) {
  9565. // Transmit children
  9566. var returnedPromise = returnedValue;
  9567. returnedPromise._moveChildren(this._children);
  9568. value = returnedPromise._result;
  9569. }
  9570. else {
  9571. value = returnedValue;
  9572. }
  9573. }
  9574. this._result = value;
  9575. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9576. var child = _a[_i];
  9577. child._resolve(value);
  9578. }
  9579. this._children.length = 0;
  9580. delete this._onFulfilled;
  9581. delete this._onRejected;
  9582. }
  9583. catch (e) {
  9584. this._reject(e, true);
  9585. }
  9586. };
  9587. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9588. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9589. this._state = PromiseStates.Rejected;
  9590. this._reason = reason;
  9591. if (this._onRejected && !onLocalThrow) {
  9592. try {
  9593. this._onRejected(reason);
  9594. this._rejectWasConsumed = true;
  9595. }
  9596. catch (e) {
  9597. reason = e;
  9598. }
  9599. }
  9600. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9601. var child = _a[_i];
  9602. if (this._rejectWasConsumed) {
  9603. child._resolve(null);
  9604. }
  9605. else {
  9606. child._reject(reason);
  9607. }
  9608. }
  9609. this._children.length = 0;
  9610. delete this._onFulfilled;
  9611. delete this._onRejected;
  9612. };
  9613. InternalPromise.resolve = function (value) {
  9614. var newPromise = new InternalPromise();
  9615. newPromise._resolve(value);
  9616. return newPromise;
  9617. };
  9618. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9619. promise.then(function (value) {
  9620. agregator.results[index] = value;
  9621. agregator.count++;
  9622. if (agregator.count === agregator.target) {
  9623. agregator.rootPromise._resolve(agregator.results);
  9624. }
  9625. return null;
  9626. }, function (reason) {
  9627. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9628. agregator.rootPromise._reject(reason);
  9629. }
  9630. });
  9631. };
  9632. InternalPromise.all = function (promises) {
  9633. var newPromise = new InternalPromise();
  9634. var agregator = new FulFillmentAgregator();
  9635. agregator.target = promises.length;
  9636. agregator.rootPromise = newPromise;
  9637. if (promises.length) {
  9638. for (var index = 0; index < promises.length; index++) {
  9639. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9640. }
  9641. }
  9642. else {
  9643. newPromise._resolve([]);
  9644. }
  9645. return newPromise;
  9646. };
  9647. InternalPromise.race = function (promises) {
  9648. var newPromise = new InternalPromise();
  9649. if (promises.length) {
  9650. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9651. var promise = promises_1[_i];
  9652. promise.then(function (value) {
  9653. if (newPromise) {
  9654. newPromise._resolve(value);
  9655. newPromise = null;
  9656. }
  9657. return null;
  9658. }, function (reason) {
  9659. if (newPromise) {
  9660. newPromise._reject(reason);
  9661. newPromise = null;
  9662. }
  9663. });
  9664. }
  9665. }
  9666. return newPromise;
  9667. };
  9668. return InternalPromise;
  9669. }());
  9670. /**
  9671. * Helper class that provides a small promise polyfill
  9672. */
  9673. var PromisePolyfill = /** @class */ (function () {
  9674. function PromisePolyfill() {
  9675. }
  9676. /**
  9677. * Static function used to check if the polyfill is required
  9678. * If this is the case then the function will inject the polyfill to window.Promise
  9679. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9680. */
  9681. PromisePolyfill.Apply = function (force) {
  9682. if (force === void 0) { force = false; }
  9683. if (force || typeof Promise === 'undefined') {
  9684. var root = window;
  9685. root.Promise = InternalPromise;
  9686. }
  9687. };
  9688. return PromisePolyfill;
  9689. }());
  9690. BABYLON.PromisePolyfill = PromisePolyfill;
  9691. })(BABYLON || (BABYLON = {}));
  9692. //# sourceMappingURL=babylon.promise.js.map
  9693. "use strict";
  9694. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9695. var BABYLON;
  9696. (function (BABYLON) {
  9697. /**
  9698. * Helper class to push actions to a pool of workers.
  9699. */
  9700. var WorkerPool = /** @class */ (function () {
  9701. /**
  9702. * Constructor
  9703. * @param workers Array of workers to use for actions
  9704. */
  9705. function WorkerPool(workers) {
  9706. this._pendingActions = new Array();
  9707. this._workerInfos = workers.map(function (worker) { return ({
  9708. worker: worker,
  9709. active: false
  9710. }); });
  9711. }
  9712. /**
  9713. * Terminates all workers and clears any pending actions.
  9714. */
  9715. WorkerPool.prototype.dispose = function () {
  9716. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9717. var workerInfo = _a[_i];
  9718. workerInfo.worker.terminate();
  9719. }
  9720. delete this._workerInfos;
  9721. delete this._pendingActions;
  9722. };
  9723. /**
  9724. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9725. * pended until a worker has completed its action.
  9726. * @param action The action to perform. Call onComplete when the action is complete.
  9727. */
  9728. WorkerPool.prototype.push = function (action) {
  9729. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9730. var workerInfo = _a[_i];
  9731. if (!workerInfo.active) {
  9732. this._execute(workerInfo, action);
  9733. return;
  9734. }
  9735. }
  9736. this._pendingActions.push(action);
  9737. };
  9738. WorkerPool.prototype._execute = function (workerInfo, action) {
  9739. var _this = this;
  9740. workerInfo.active = true;
  9741. action(workerInfo.worker, function () {
  9742. workerInfo.active = false;
  9743. var nextAction = _this._pendingActions.shift();
  9744. if (nextAction) {
  9745. _this._execute(workerInfo, nextAction);
  9746. }
  9747. });
  9748. };
  9749. return WorkerPool;
  9750. }());
  9751. BABYLON.WorkerPool = WorkerPool;
  9752. })(BABYLON || (BABYLON = {}));
  9753. //# sourceMappingURL=babylon.workerPool.js.map
  9754. "use strict";
  9755. var BABYLON;
  9756. (function (BABYLON) {
  9757. var _AlphaState = /** @class */ (function () {
  9758. /**
  9759. * Initializes the state.
  9760. */
  9761. function _AlphaState() {
  9762. this._isAlphaBlendDirty = false;
  9763. this._isBlendFunctionParametersDirty = false;
  9764. this._isBlendEquationParametersDirty = false;
  9765. this._isBlendConstantsDirty = false;
  9766. this._alphaBlend = false;
  9767. this._blendFunctionParameters = new Array(4);
  9768. this._blendEquationParameters = new Array(2);
  9769. this._blendConstants = new Array(4);
  9770. this.reset();
  9771. }
  9772. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9773. get: function () {
  9774. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9775. },
  9776. enumerable: true,
  9777. configurable: true
  9778. });
  9779. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9780. get: function () {
  9781. return this._alphaBlend;
  9782. },
  9783. set: function (value) {
  9784. if (this._alphaBlend === value) {
  9785. return;
  9786. }
  9787. this._alphaBlend = value;
  9788. this._isAlphaBlendDirty = true;
  9789. },
  9790. enumerable: true,
  9791. configurable: true
  9792. });
  9793. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9794. if (this._blendConstants[0] === r &&
  9795. this._blendConstants[1] === g &&
  9796. this._blendConstants[2] === b &&
  9797. this._blendConstants[3] === a) {
  9798. return;
  9799. }
  9800. this._blendConstants[0] = r;
  9801. this._blendConstants[1] = g;
  9802. this._blendConstants[2] = b;
  9803. this._blendConstants[3] = a;
  9804. this._isBlendConstantsDirty = true;
  9805. };
  9806. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9807. if (this._blendFunctionParameters[0] === value0 &&
  9808. this._blendFunctionParameters[1] === value1 &&
  9809. this._blendFunctionParameters[2] === value2 &&
  9810. this._blendFunctionParameters[3] === value3) {
  9811. return;
  9812. }
  9813. this._blendFunctionParameters[0] = value0;
  9814. this._blendFunctionParameters[1] = value1;
  9815. this._blendFunctionParameters[2] = value2;
  9816. this._blendFunctionParameters[3] = value3;
  9817. this._isBlendFunctionParametersDirty = true;
  9818. };
  9819. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9820. if (this._blendEquationParameters[0] === rgb &&
  9821. this._blendEquationParameters[1] === alpha) {
  9822. return;
  9823. }
  9824. this._blendEquationParameters[0] = rgb;
  9825. this._blendEquationParameters[1] = alpha;
  9826. this._isBlendEquationParametersDirty = true;
  9827. };
  9828. _AlphaState.prototype.reset = function () {
  9829. this._alphaBlend = false;
  9830. this._blendFunctionParameters[0] = null;
  9831. this._blendFunctionParameters[1] = null;
  9832. this._blendFunctionParameters[2] = null;
  9833. this._blendFunctionParameters[3] = null;
  9834. this._blendEquationParameters[0] = null;
  9835. this._blendEquationParameters[1] = null;
  9836. this._blendConstants[0] = null;
  9837. this._blendConstants[1] = null;
  9838. this._blendConstants[2] = null;
  9839. this._blendConstants[3] = null;
  9840. this._isAlphaBlendDirty = true;
  9841. this._isBlendFunctionParametersDirty = false;
  9842. this._isBlendEquationParametersDirty = false;
  9843. this._isBlendConstantsDirty = false;
  9844. };
  9845. _AlphaState.prototype.apply = function (gl) {
  9846. if (!this.isDirty) {
  9847. return;
  9848. }
  9849. // Alpha blend
  9850. if (this._isAlphaBlendDirty) {
  9851. if (this._alphaBlend) {
  9852. gl.enable(gl.BLEND);
  9853. }
  9854. else {
  9855. gl.disable(gl.BLEND);
  9856. }
  9857. this._isAlphaBlendDirty = false;
  9858. }
  9859. // Alpha function
  9860. if (this._isBlendFunctionParametersDirty) {
  9861. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9862. this._isBlendFunctionParametersDirty = false;
  9863. }
  9864. // Alpha equation
  9865. if (this._isBlendEquationParametersDirty) {
  9866. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9867. this._isBlendEquationParametersDirty = false;
  9868. }
  9869. // Constants
  9870. if (this._isBlendConstantsDirty) {
  9871. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9872. this._isBlendConstantsDirty = false;
  9873. }
  9874. };
  9875. return _AlphaState;
  9876. }());
  9877. BABYLON._AlphaState = _AlphaState;
  9878. })(BABYLON || (BABYLON = {}));
  9879. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9880. "use strict";
  9881. var BABYLON;
  9882. (function (BABYLON) {
  9883. var _DepthCullingState = /** @class */ (function () {
  9884. /**
  9885. * Initializes the state.
  9886. */
  9887. function _DepthCullingState() {
  9888. this._isDepthTestDirty = false;
  9889. this._isDepthMaskDirty = false;
  9890. this._isDepthFuncDirty = false;
  9891. this._isCullFaceDirty = false;
  9892. this._isCullDirty = false;
  9893. this._isZOffsetDirty = false;
  9894. this._isFrontFaceDirty = false;
  9895. this.reset();
  9896. }
  9897. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9898. get: function () {
  9899. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9905. get: function () {
  9906. return this._zOffset;
  9907. },
  9908. set: function (value) {
  9909. if (this._zOffset === value) {
  9910. return;
  9911. }
  9912. this._zOffset = value;
  9913. this._isZOffsetDirty = true;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9919. get: function () {
  9920. return this._cullFace;
  9921. },
  9922. set: function (value) {
  9923. if (this._cullFace === value) {
  9924. return;
  9925. }
  9926. this._cullFace = value;
  9927. this._isCullFaceDirty = true;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9933. get: function () {
  9934. return this._cull;
  9935. },
  9936. set: function (value) {
  9937. if (this._cull === value) {
  9938. return;
  9939. }
  9940. this._cull = value;
  9941. this._isCullDirty = true;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9947. get: function () {
  9948. return this._depthFunc;
  9949. },
  9950. set: function (value) {
  9951. if (this._depthFunc === value) {
  9952. return;
  9953. }
  9954. this._depthFunc = value;
  9955. this._isDepthFuncDirty = true;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9961. get: function () {
  9962. return this._depthMask;
  9963. },
  9964. set: function (value) {
  9965. if (this._depthMask === value) {
  9966. return;
  9967. }
  9968. this._depthMask = value;
  9969. this._isDepthMaskDirty = true;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9975. get: function () {
  9976. return this._depthTest;
  9977. },
  9978. set: function (value) {
  9979. if (this._depthTest === value) {
  9980. return;
  9981. }
  9982. this._depthTest = value;
  9983. this._isDepthTestDirty = true;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9989. get: function () {
  9990. return this._frontFace;
  9991. },
  9992. set: function (value) {
  9993. if (this._frontFace === value) {
  9994. return;
  9995. }
  9996. this._frontFace = value;
  9997. this._isFrontFaceDirty = true;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. _DepthCullingState.prototype.reset = function () {
  10003. this._depthMask = true;
  10004. this._depthTest = true;
  10005. this._depthFunc = null;
  10006. this._cullFace = null;
  10007. this._cull = null;
  10008. this._zOffset = 0;
  10009. this._frontFace = null;
  10010. this._isDepthTestDirty = true;
  10011. this._isDepthMaskDirty = true;
  10012. this._isDepthFuncDirty = false;
  10013. this._isCullFaceDirty = false;
  10014. this._isCullDirty = false;
  10015. this._isZOffsetDirty = false;
  10016. this._isFrontFaceDirty = false;
  10017. };
  10018. _DepthCullingState.prototype.apply = function (gl) {
  10019. if (!this.isDirty) {
  10020. return;
  10021. }
  10022. // Cull
  10023. if (this._isCullDirty) {
  10024. if (this.cull) {
  10025. gl.enable(gl.CULL_FACE);
  10026. }
  10027. else {
  10028. gl.disable(gl.CULL_FACE);
  10029. }
  10030. this._isCullDirty = false;
  10031. }
  10032. // Cull face
  10033. if (this._isCullFaceDirty) {
  10034. gl.cullFace(this.cullFace);
  10035. this._isCullFaceDirty = false;
  10036. }
  10037. // Depth mask
  10038. if (this._isDepthMaskDirty) {
  10039. gl.depthMask(this.depthMask);
  10040. this._isDepthMaskDirty = false;
  10041. }
  10042. // Depth test
  10043. if (this._isDepthTestDirty) {
  10044. if (this.depthTest) {
  10045. gl.enable(gl.DEPTH_TEST);
  10046. }
  10047. else {
  10048. gl.disable(gl.DEPTH_TEST);
  10049. }
  10050. this._isDepthTestDirty = false;
  10051. }
  10052. // Depth func
  10053. if (this._isDepthFuncDirty) {
  10054. gl.depthFunc(this.depthFunc);
  10055. this._isDepthFuncDirty = false;
  10056. }
  10057. // zOffset
  10058. if (this._isZOffsetDirty) {
  10059. if (this.zOffset) {
  10060. gl.enable(gl.POLYGON_OFFSET_FILL);
  10061. gl.polygonOffset(this.zOffset, 0);
  10062. }
  10063. else {
  10064. gl.disable(gl.POLYGON_OFFSET_FILL);
  10065. }
  10066. this._isZOffsetDirty = false;
  10067. }
  10068. // Front face
  10069. if (this._isFrontFaceDirty) {
  10070. gl.frontFace(this.frontFace);
  10071. this._isFrontFaceDirty = false;
  10072. }
  10073. };
  10074. return _DepthCullingState;
  10075. }());
  10076. BABYLON._DepthCullingState = _DepthCullingState;
  10077. })(BABYLON || (BABYLON = {}));
  10078. //# sourceMappingURL=babylon.depthCullingState.js.map
  10079. "use strict";
  10080. var BABYLON;
  10081. (function (BABYLON) {
  10082. var _StencilState = /** @class */ (function () {
  10083. function _StencilState() {
  10084. this._isStencilTestDirty = false;
  10085. this._isStencilMaskDirty = false;
  10086. this._isStencilFuncDirty = false;
  10087. this._isStencilOpDirty = false;
  10088. this.reset();
  10089. }
  10090. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10091. get: function () {
  10092. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10093. },
  10094. enumerable: true,
  10095. configurable: true
  10096. });
  10097. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10098. get: function () {
  10099. return this._stencilFunc;
  10100. },
  10101. set: function (value) {
  10102. if (this._stencilFunc === value) {
  10103. return;
  10104. }
  10105. this._stencilFunc = value;
  10106. this._isStencilFuncDirty = true;
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10112. get: function () {
  10113. return this._stencilFuncRef;
  10114. },
  10115. set: function (value) {
  10116. if (this._stencilFuncRef === value) {
  10117. return;
  10118. }
  10119. this._stencilFuncRef = value;
  10120. this._isStencilFuncDirty = true;
  10121. },
  10122. enumerable: true,
  10123. configurable: true
  10124. });
  10125. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10126. get: function () {
  10127. return this._stencilFuncMask;
  10128. },
  10129. set: function (value) {
  10130. if (this._stencilFuncMask === value) {
  10131. return;
  10132. }
  10133. this._stencilFuncMask = value;
  10134. this._isStencilFuncDirty = true;
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10140. get: function () {
  10141. return this._stencilOpStencilFail;
  10142. },
  10143. set: function (value) {
  10144. if (this._stencilOpStencilFail === value) {
  10145. return;
  10146. }
  10147. this._stencilOpStencilFail = value;
  10148. this._isStencilOpDirty = true;
  10149. },
  10150. enumerable: true,
  10151. configurable: true
  10152. });
  10153. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10154. get: function () {
  10155. return this._stencilOpDepthFail;
  10156. },
  10157. set: function (value) {
  10158. if (this._stencilOpDepthFail === value) {
  10159. return;
  10160. }
  10161. this._stencilOpDepthFail = value;
  10162. this._isStencilOpDirty = true;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10168. get: function () {
  10169. return this._stencilOpStencilDepthPass;
  10170. },
  10171. set: function (value) {
  10172. if (this._stencilOpStencilDepthPass === value) {
  10173. return;
  10174. }
  10175. this._stencilOpStencilDepthPass = value;
  10176. this._isStencilOpDirty = true;
  10177. },
  10178. enumerable: true,
  10179. configurable: true
  10180. });
  10181. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10182. get: function () {
  10183. return this._stencilMask;
  10184. },
  10185. set: function (value) {
  10186. if (this._stencilMask === value) {
  10187. return;
  10188. }
  10189. this._stencilMask = value;
  10190. this._isStencilMaskDirty = true;
  10191. },
  10192. enumerable: true,
  10193. configurable: true
  10194. });
  10195. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10196. get: function () {
  10197. return this._stencilTest;
  10198. },
  10199. set: function (value) {
  10200. if (this._stencilTest === value) {
  10201. return;
  10202. }
  10203. this._stencilTest = value;
  10204. this._isStencilTestDirty = true;
  10205. },
  10206. enumerable: true,
  10207. configurable: true
  10208. });
  10209. _StencilState.prototype.reset = function () {
  10210. this._stencilTest = false;
  10211. this._stencilMask = 0xFF;
  10212. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10213. this._stencilFuncRef = 1;
  10214. this._stencilFuncMask = 0xFF;
  10215. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10216. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10217. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10218. this._isStencilTestDirty = true;
  10219. this._isStencilMaskDirty = true;
  10220. this._isStencilFuncDirty = true;
  10221. this._isStencilOpDirty = true;
  10222. };
  10223. _StencilState.prototype.apply = function (gl) {
  10224. if (!this.isDirty) {
  10225. return;
  10226. }
  10227. // Stencil test
  10228. if (this._isStencilTestDirty) {
  10229. if (this.stencilTest) {
  10230. gl.enable(gl.STENCIL_TEST);
  10231. }
  10232. else {
  10233. gl.disable(gl.STENCIL_TEST);
  10234. }
  10235. this._isStencilTestDirty = false;
  10236. }
  10237. // Stencil mask
  10238. if (this._isStencilMaskDirty) {
  10239. gl.stencilMask(this.stencilMask);
  10240. this._isStencilMaskDirty = false;
  10241. }
  10242. // Stencil func
  10243. if (this._isStencilFuncDirty) {
  10244. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10245. this._isStencilFuncDirty = false;
  10246. }
  10247. // Stencil op
  10248. if (this._isStencilOpDirty) {
  10249. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10250. this._isStencilOpDirty = false;
  10251. }
  10252. };
  10253. return _StencilState;
  10254. }());
  10255. BABYLON._StencilState = _StencilState;
  10256. })(BABYLON || (BABYLON = {}));
  10257. //# sourceMappingURL=babylon.stencilState.js.map
  10258. "use strict";
  10259. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10260. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10261. s = arguments[i];
  10262. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10263. t[p] = s[p];
  10264. }
  10265. return t;
  10266. };
  10267. var BABYLON;
  10268. (function (BABYLON) {
  10269. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10270. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10271. };
  10272. var compileRawShader = function (gl, source, type) {
  10273. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10274. gl.shaderSource(shader, source);
  10275. gl.compileShader(shader);
  10276. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10277. var log = gl.getShaderInfoLog(shader);
  10278. if (log) {
  10279. throw new Error(log);
  10280. }
  10281. }
  10282. if (!shader) {
  10283. throw new Error("Something went wrong while compile the shader.");
  10284. }
  10285. return shader;
  10286. };
  10287. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10288. var magFilter = gl.NEAREST;
  10289. var minFilter = gl.NEAREST;
  10290. switch (samplingMode) {
  10291. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10292. magFilter = gl.LINEAR;
  10293. if (generateMipMaps) {
  10294. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10295. }
  10296. else {
  10297. minFilter = gl.LINEAR;
  10298. }
  10299. break;
  10300. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10301. magFilter = gl.LINEAR;
  10302. if (generateMipMaps) {
  10303. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10304. }
  10305. else {
  10306. minFilter = gl.LINEAR;
  10307. }
  10308. break;
  10309. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10310. magFilter = gl.NEAREST;
  10311. if (generateMipMaps) {
  10312. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10313. }
  10314. else {
  10315. minFilter = gl.NEAREST;
  10316. }
  10317. break;
  10318. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10319. magFilter = gl.NEAREST;
  10320. if (generateMipMaps) {
  10321. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10322. }
  10323. else {
  10324. minFilter = gl.NEAREST;
  10325. }
  10326. break;
  10327. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10328. magFilter = gl.NEAREST;
  10329. if (generateMipMaps) {
  10330. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10331. }
  10332. else {
  10333. minFilter = gl.LINEAR;
  10334. }
  10335. break;
  10336. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10337. magFilter = gl.NEAREST;
  10338. if (generateMipMaps) {
  10339. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10340. }
  10341. else {
  10342. minFilter = gl.LINEAR;
  10343. }
  10344. break;
  10345. case BABYLON.Texture.NEAREST_LINEAR:
  10346. magFilter = gl.NEAREST;
  10347. minFilter = gl.LINEAR;
  10348. break;
  10349. case BABYLON.Texture.NEAREST_NEAREST:
  10350. magFilter = gl.NEAREST;
  10351. minFilter = gl.NEAREST;
  10352. break;
  10353. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10354. magFilter = gl.LINEAR;
  10355. if (generateMipMaps) {
  10356. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10357. }
  10358. else {
  10359. minFilter = gl.NEAREST;
  10360. }
  10361. break;
  10362. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10363. magFilter = gl.LINEAR;
  10364. if (generateMipMaps) {
  10365. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10366. }
  10367. else {
  10368. minFilter = gl.NEAREST;
  10369. }
  10370. break;
  10371. case BABYLON.Texture.LINEAR_LINEAR:
  10372. magFilter = gl.LINEAR;
  10373. minFilter = gl.LINEAR;
  10374. break;
  10375. case BABYLON.Texture.LINEAR_NEAREST:
  10376. magFilter = gl.LINEAR;
  10377. minFilter = gl.NEAREST;
  10378. break;
  10379. }
  10380. return {
  10381. min: minFilter,
  10382. mag: magFilter
  10383. };
  10384. };
  10385. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10386. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10387. var img;
  10388. var onload = function () {
  10389. loadedImages[index] = img;
  10390. loadedImages._internalCount++;
  10391. if (scene) {
  10392. scene._removePendingData(img);
  10393. }
  10394. if (loadedImages._internalCount === 6) {
  10395. onfinish(loadedImages);
  10396. }
  10397. };
  10398. var onerror = function (message, exception) {
  10399. if (scene) {
  10400. scene._removePendingData(img);
  10401. }
  10402. if (onErrorCallBack) {
  10403. onErrorCallBack(message, exception);
  10404. }
  10405. };
  10406. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10407. if (scene) {
  10408. scene._addPendingData(img);
  10409. }
  10410. };
  10411. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10412. if (onError === void 0) { onError = null; }
  10413. var loadedImages = [];
  10414. loadedImages._internalCount = 0;
  10415. for (var index = 0; index < 6; index++) {
  10416. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10417. }
  10418. };
  10419. var BufferPointer = /** @class */ (function () {
  10420. function BufferPointer() {
  10421. }
  10422. return BufferPointer;
  10423. }());
  10424. var InstancingAttributeInfo = /** @class */ (function () {
  10425. function InstancingAttributeInfo() {
  10426. }
  10427. return InstancingAttributeInfo;
  10428. }());
  10429. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10430. /**
  10431. * Define options used to create a render target texture
  10432. */
  10433. var RenderTargetCreationOptions = /** @class */ (function () {
  10434. function RenderTargetCreationOptions() {
  10435. }
  10436. return RenderTargetCreationOptions;
  10437. }());
  10438. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10439. /**
  10440. * Define options used to create a depth texture
  10441. */
  10442. var DepthTextureCreationOptions = /** @class */ (function () {
  10443. function DepthTextureCreationOptions() {
  10444. }
  10445. return DepthTextureCreationOptions;
  10446. }());
  10447. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10448. /**
  10449. * Regroup several parameters relative to the browser in use
  10450. */
  10451. var EngineCapabilities = /** @class */ (function () {
  10452. function EngineCapabilities() {
  10453. }
  10454. return EngineCapabilities;
  10455. }());
  10456. BABYLON.EngineCapabilities = EngineCapabilities;
  10457. /**
  10458. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10459. */
  10460. var Engine = /** @class */ (function () {
  10461. /**
  10462. * @constructor
  10463. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10464. * @param antialias defines enable antialiasing (default: false)
  10465. * @param options defines further options to be sent to the getContext() function
  10466. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10467. */
  10468. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10469. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10470. var _this = this;
  10471. // Public members
  10472. this.forcePOTTextures = false;
  10473. this.isFullscreen = false;
  10474. this.isPointerLock = false;
  10475. this.cullBackFaces = true;
  10476. this.renderEvenInBackground = true;
  10477. this.preventCacheWipeBetweenFrames = false;
  10478. /**
  10479. * To enable/disable IDB support and avoid XHR on .manifest
  10480. **/
  10481. this.enableOfflineSupport = false;
  10482. this.scenes = new Array();
  10483. this.postProcesses = new Array();
  10484. // Observables
  10485. /**
  10486. * Observable event triggered each time the rendering canvas is resized
  10487. */
  10488. this.onResizeObservable = new BABYLON.Observable();
  10489. /**
  10490. * Observable event triggered each time the canvas loses focus
  10491. */
  10492. this.onCanvasBlurObservable = new BABYLON.Observable();
  10493. /**
  10494. * Observable event triggered each time the canvas gains focus
  10495. */
  10496. this.onCanvasFocusObservable = new BABYLON.Observable();
  10497. /**
  10498. * Observable event triggered each time the canvas receives pointerout event
  10499. */
  10500. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10501. /**
  10502. * Observable event triggered before each texture is initialized
  10503. */
  10504. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10505. //WebVR
  10506. this._vrDisplay = undefined;
  10507. this._vrSupported = false;
  10508. this._vrExclusivePointerMode = false;
  10509. // Uniform buffers list
  10510. this.disableUniformBuffers = false;
  10511. this._uniformBuffers = new Array();
  10512. // Observables
  10513. /**
  10514. * Observable raised when the engine begins a new frame
  10515. */
  10516. this.onBeginFrameObservable = new BABYLON.Observable();
  10517. /**
  10518. * Observable raised when the engine ends the current frame
  10519. */
  10520. this.onEndFrameObservable = new BABYLON.Observable();
  10521. /**
  10522. * Observable raised when the engine is about to compile a shader
  10523. */
  10524. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10525. /**
  10526. * Observable raised when the engine has jsut compiled a shader
  10527. */
  10528. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10529. this._windowIsBackground = false;
  10530. this._webGLVersion = 1.0;
  10531. this._badOS = false;
  10532. this._badDesktopOS = false;
  10533. /**
  10534. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10535. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10536. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10537. */
  10538. this.disableTextureBindingOptimization = false;
  10539. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10540. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10541. this.onVRRequestPresentStart = new BABYLON.Observable();
  10542. this._colorWrite = true;
  10543. this._drawCalls = new BABYLON.PerfCounter();
  10544. this._textureCollisions = new BABYLON.PerfCounter();
  10545. this._renderingQueueLaunched = false;
  10546. this._activeRenderLoops = new Array();
  10547. // Deterministic lockstepMaxSteps
  10548. this._deterministicLockstep = false;
  10549. this._lockstepMaxSteps = 4;
  10550. // Lost context
  10551. this.onContextLostObservable = new BABYLON.Observable();
  10552. this.onContextRestoredObservable = new BABYLON.Observable();
  10553. this._contextWasLost = false;
  10554. this._doNotHandleContextLost = false;
  10555. // FPS
  10556. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10557. this._fps = 60;
  10558. this._deltaTime = 0;
  10559. /**
  10560. * Turn this value on if you want to pause FPS computation when in background
  10561. */
  10562. this.disablePerformanceMonitorInBackground = false;
  10563. // States
  10564. this._depthCullingState = new BABYLON._DepthCullingState();
  10565. this._stencilState = new BABYLON._StencilState();
  10566. this._alphaState = new BABYLON._AlphaState();
  10567. this._alphaMode = Engine.ALPHA_DISABLE;
  10568. // Cache
  10569. this._internalTexturesCache = new Array();
  10570. this._activeChannel = 0;
  10571. this._currentTextureChannel = -1;
  10572. this._boundTexturesCache = {};
  10573. this._compiledEffects = {};
  10574. this._vertexAttribArraysEnabled = [];
  10575. this._uintIndicesCurrentlySet = false;
  10576. this._currentBoundBuffer = new Array();
  10577. this._currentBufferPointers = new Array();
  10578. this._currentInstanceLocations = new Array();
  10579. this._currentInstanceBuffers = new Array();
  10580. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10581. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10582. this._vaoRecordInProgress = false;
  10583. this._mustWipeVertexAttributes = false;
  10584. this._nextFreeTextureSlots = new Array();
  10585. this._maxSimultaneousTextures = 0;
  10586. this._activeRequests = new Array();
  10587. // Hardware supported Compressed Textures
  10588. this._texturesSupported = new Array();
  10589. this._onVRFullScreenTriggered = function () {
  10590. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10591. //get the old size before we change
  10592. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10593. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10594. //get the width and height, change the render size
  10595. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10596. _this.setHardwareScalingLevel(1);
  10597. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10598. }
  10599. else {
  10600. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10601. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10602. }
  10603. };
  10604. this._boundUniforms = {};
  10605. // Register promises
  10606. BABYLON.PromisePolyfill.Apply();
  10607. var canvas = null;
  10608. Engine.Instances.push(this);
  10609. if (!canvasOrContext) {
  10610. return;
  10611. }
  10612. options = options || {};
  10613. if (canvasOrContext.getContext) {
  10614. canvas = canvasOrContext;
  10615. this._renderingCanvas = canvas;
  10616. if (antialias != null) {
  10617. options.antialias = antialias;
  10618. }
  10619. if (options.deterministicLockstep === undefined) {
  10620. options.deterministicLockstep = false;
  10621. }
  10622. if (options.lockstepMaxSteps === undefined) {
  10623. options.lockstepMaxSteps = 4;
  10624. }
  10625. if (options.preserveDrawingBuffer === undefined) {
  10626. options.preserveDrawingBuffer = false;
  10627. }
  10628. if (options.audioEngine === undefined) {
  10629. options.audioEngine = true;
  10630. }
  10631. if (options.stencil === undefined) {
  10632. options.stencil = true;
  10633. }
  10634. this._deterministicLockstep = options.deterministicLockstep;
  10635. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10636. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10637. // Exceptions
  10638. if (navigator && navigator.userAgent) {
  10639. var ua = navigator.userAgent;
  10640. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10641. var exception = _a[_i];
  10642. var key = exception.key;
  10643. var targets = exception.targets;
  10644. if (ua.indexOf(key) > -1) {
  10645. if (exception.capture && exception.captureConstraint) {
  10646. var capture = exception.capture;
  10647. var constraint = exception.captureConstraint;
  10648. var regex = new RegExp(capture);
  10649. var matches = regex.exec(ua);
  10650. if (matches && matches.length > 0) {
  10651. var capturedValue = parseInt(matches[matches.length - 1]);
  10652. if (capturedValue >= constraint) {
  10653. continue;
  10654. }
  10655. }
  10656. }
  10657. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10658. var target = targets_1[_b];
  10659. switch (target) {
  10660. case "uniformBuffer":
  10661. this.disableUniformBuffers = true;
  10662. break;
  10663. case "textureBindingOptimization":
  10664. this.disableTextureBindingOptimization = true;
  10665. break;
  10666. }
  10667. }
  10668. }
  10669. }
  10670. }
  10671. // GL
  10672. if (!options.disableWebGL2Support) {
  10673. try {
  10674. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10675. if (this._gl) {
  10676. this._webGLVersion = 2.0;
  10677. }
  10678. }
  10679. catch (e) {
  10680. // Do nothing
  10681. }
  10682. }
  10683. if (!this._gl) {
  10684. if (!canvas) {
  10685. throw new Error("The provided canvas is null or undefined.");
  10686. }
  10687. try {
  10688. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10689. }
  10690. catch (e) {
  10691. throw new Error("WebGL not supported");
  10692. }
  10693. }
  10694. if (!this._gl) {
  10695. throw new Error("WebGL not supported");
  10696. }
  10697. this._onCanvasFocus = function () {
  10698. _this.onCanvasFocusObservable.notifyObservers(_this);
  10699. };
  10700. this._onCanvasBlur = function () {
  10701. _this.onCanvasBlurObservable.notifyObservers(_this);
  10702. };
  10703. canvas.addEventListener("focus", this._onCanvasFocus);
  10704. canvas.addEventListener("blur", this._onCanvasBlur);
  10705. this._onBlur = function () {
  10706. if (_this.disablePerformanceMonitorInBackground) {
  10707. _this._performanceMonitor.disable();
  10708. }
  10709. _this._windowIsBackground = true;
  10710. };
  10711. this._onFocus = function () {
  10712. if (_this.disablePerformanceMonitorInBackground) {
  10713. _this._performanceMonitor.enable();
  10714. }
  10715. _this._windowIsBackground = false;
  10716. };
  10717. this._onCanvasPointerOut = function (ev) {
  10718. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10719. };
  10720. window.addEventListener("blur", this._onBlur);
  10721. window.addEventListener("focus", this._onFocus);
  10722. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10723. // Context lost
  10724. if (!this._doNotHandleContextLost) {
  10725. this._onContextLost = function (evt) {
  10726. evt.preventDefault();
  10727. _this._contextWasLost = true;
  10728. BABYLON.Tools.Warn("WebGL context lost.");
  10729. _this.onContextLostObservable.notifyObservers(_this);
  10730. };
  10731. this._onContextRestored = function (evt) {
  10732. // Adding a timeout to avoid race condition at browser level
  10733. setTimeout(function () {
  10734. // Rebuild gl context
  10735. _this._initGLContext();
  10736. // Rebuild effects
  10737. _this._rebuildEffects();
  10738. // Rebuild textures
  10739. _this._rebuildInternalTextures();
  10740. // Rebuild buffers
  10741. _this._rebuildBuffers();
  10742. // Cache
  10743. _this.wipeCaches(true);
  10744. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10745. _this.onContextRestoredObservable.notifyObservers(_this);
  10746. _this._contextWasLost = false;
  10747. }, 0);
  10748. };
  10749. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10750. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10751. }
  10752. }
  10753. else {
  10754. this._gl = canvasOrContext;
  10755. this._renderingCanvas = this._gl.canvas;
  10756. if (this._gl.renderbufferStorageMultisample) {
  10757. this._webGLVersion = 2.0;
  10758. }
  10759. options.stencil = this._gl.getContextAttributes().stencil;
  10760. }
  10761. // Viewport
  10762. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10763. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10764. this.resize();
  10765. this._isStencilEnable = options.stencil ? true : false;
  10766. this._initGLContext();
  10767. if (canvas) {
  10768. // Fullscreen
  10769. this._onFullscreenChange = function () {
  10770. if (document.fullscreen !== undefined) {
  10771. _this.isFullscreen = document.fullscreen;
  10772. }
  10773. else if (document.mozFullScreen !== undefined) {
  10774. _this.isFullscreen = document.mozFullScreen;
  10775. }
  10776. else if (document.webkitIsFullScreen !== undefined) {
  10777. _this.isFullscreen = document.webkitIsFullScreen;
  10778. }
  10779. else if (document.msIsFullScreen !== undefined) {
  10780. _this.isFullscreen = document.msIsFullScreen;
  10781. }
  10782. // Pointer lock
  10783. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10784. canvas.requestPointerLock = canvas.requestPointerLock ||
  10785. canvas.msRequestPointerLock ||
  10786. canvas.mozRequestPointerLock ||
  10787. canvas.webkitRequestPointerLock;
  10788. if (canvas.requestPointerLock) {
  10789. canvas.requestPointerLock();
  10790. }
  10791. }
  10792. };
  10793. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10794. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10795. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10796. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10797. // Pointer lock
  10798. this._onPointerLockChange = function () {
  10799. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10800. document.webkitPointerLockElement === canvas ||
  10801. document.msPointerLockElement === canvas ||
  10802. document.pointerLockElement === canvas);
  10803. };
  10804. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10805. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10806. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10807. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10808. this._onVRDisplayPointerRestricted = function () {
  10809. if (canvas) {
  10810. canvas.requestPointerLock();
  10811. }
  10812. };
  10813. this._onVRDisplayPointerUnrestricted = function () {
  10814. document.exitPointerLock();
  10815. };
  10816. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10817. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10818. }
  10819. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10820. Engine.audioEngine = new BABYLON.AudioEngine();
  10821. }
  10822. // Prepare buffer pointers
  10823. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10824. this._currentBufferPointers[i] = new BufferPointer();
  10825. }
  10826. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10827. // Load WebVR Devices
  10828. if (options.autoEnableWebVR) {
  10829. this.initWebVR();
  10830. }
  10831. // Detect if we are running on a faulty buggy OS.
  10832. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10833. // Detect if we are running on a faulty buggy desktop OS.
  10834. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10835. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10836. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10837. }
  10838. Object.defineProperty(Engine, "LastCreatedEngine", {
  10839. get: function () {
  10840. if (Engine.Instances.length === 0) {
  10841. return null;
  10842. }
  10843. return Engine.Instances[Engine.Instances.length - 1];
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "LastCreatedScene", {
  10849. get: function () {
  10850. var lastCreatedEngine = Engine.LastCreatedEngine;
  10851. if (!lastCreatedEngine) {
  10852. return null;
  10853. }
  10854. if (lastCreatedEngine.scenes.length === 0) {
  10855. return null;
  10856. }
  10857. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. /**
  10863. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10864. */
  10865. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10866. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10867. var engine = Engine.Instances[engineIndex];
  10868. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10869. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10870. }
  10871. }
  10872. };
  10873. Object.defineProperty(Engine, "NEVER", {
  10874. get: function () {
  10875. return Engine._NEVER;
  10876. },
  10877. enumerable: true,
  10878. configurable: true
  10879. });
  10880. Object.defineProperty(Engine, "ALWAYS", {
  10881. get: function () {
  10882. return Engine._ALWAYS;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(Engine, "LESS", {
  10888. get: function () {
  10889. return Engine._LESS;
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. Object.defineProperty(Engine, "EQUAL", {
  10895. get: function () {
  10896. return Engine._EQUAL;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(Engine, "LEQUAL", {
  10902. get: function () {
  10903. return Engine._LEQUAL;
  10904. },
  10905. enumerable: true,
  10906. configurable: true
  10907. });
  10908. Object.defineProperty(Engine, "GREATER", {
  10909. get: function () {
  10910. return Engine._GREATER;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(Engine, "GEQUAL", {
  10916. get: function () {
  10917. return Engine._GEQUAL;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(Engine, "NOTEQUAL", {
  10923. get: function () {
  10924. return Engine._NOTEQUAL;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(Engine, "KEEP", {
  10930. get: function () {
  10931. return Engine._KEEP;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(Engine, "REPLACE", {
  10937. get: function () {
  10938. return Engine._REPLACE;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(Engine, "INCR", {
  10944. get: function () {
  10945. return Engine._INCR;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(Engine, "DECR", {
  10951. get: function () {
  10952. return Engine._DECR;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(Engine, "INVERT", {
  10958. get: function () {
  10959. return Engine._INVERT;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(Engine, "INCR_WRAP", {
  10965. get: function () {
  10966. return Engine._INCR_WRAP;
  10967. },
  10968. enumerable: true,
  10969. configurable: true
  10970. });
  10971. Object.defineProperty(Engine, "DECR_WRAP", {
  10972. get: function () {
  10973. return Engine._DECR_WRAP;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10979. get: function () {
  10980. return Engine._ALPHA_DISABLE;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10986. get: function () {
  10987. return Engine._ALPHA_ONEONE;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Engine, "ALPHA_ADD", {
  10993. get: function () {
  10994. return Engine._ALPHA_ADD;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11000. get: function () {
  11001. return Engine._ALPHA_COMBINE;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11007. get: function () {
  11008. return Engine._ALPHA_SUBTRACT;
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11014. get: function () {
  11015. return Engine._ALPHA_MULTIPLY;
  11016. },
  11017. enumerable: true,
  11018. configurable: true
  11019. });
  11020. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11021. get: function () {
  11022. return Engine._ALPHA_MAXIMIZED;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11028. get: function () {
  11029. return Engine._ALPHA_PREMULTIPLIED;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11035. get: function () {
  11036. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11037. },
  11038. enumerable: true,
  11039. configurable: true
  11040. });
  11041. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11042. get: function () {
  11043. return Engine._ALPHA_INTERPOLATE;
  11044. },
  11045. enumerable: true,
  11046. configurable: true
  11047. });
  11048. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11049. get: function () {
  11050. return Engine._ALPHA_SCREENMODE;
  11051. },
  11052. enumerable: true,
  11053. configurable: true
  11054. });
  11055. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11056. get: function () {
  11057. return Engine._DELAYLOADSTATE_NONE;
  11058. },
  11059. enumerable: true,
  11060. configurable: true
  11061. });
  11062. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11063. get: function () {
  11064. return Engine._DELAYLOADSTATE_LOADED;
  11065. },
  11066. enumerable: true,
  11067. configurable: true
  11068. });
  11069. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11070. get: function () {
  11071. return Engine._DELAYLOADSTATE_LOADING;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11077. get: function () {
  11078. return Engine._DELAYLOADSTATE_NOTLOADED;
  11079. },
  11080. enumerable: true,
  11081. configurable: true
  11082. });
  11083. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11084. get: function () {
  11085. return Engine._TEXTUREFORMAT_ALPHA;
  11086. },
  11087. enumerable: true,
  11088. configurable: true
  11089. });
  11090. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11091. get: function () {
  11092. return Engine._TEXTUREFORMAT_LUMINANCE;
  11093. },
  11094. enumerable: true,
  11095. configurable: true
  11096. });
  11097. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11098. /**
  11099. * R32F
  11100. */
  11101. get: function () {
  11102. return Engine._TEXTUREFORMAT_R32F;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11108. /**
  11109. * RG32F
  11110. */
  11111. get: function () {
  11112. return Engine._TEXTUREFORMAT_RG32F;
  11113. },
  11114. enumerable: true,
  11115. configurable: true
  11116. });
  11117. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11118. /**
  11119. * RGB32F
  11120. */
  11121. get: function () {
  11122. return Engine._TEXTUREFORMAT_RGB32F;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11128. /**
  11129. * RGBA32F
  11130. */
  11131. get: function () {
  11132. return Engine._TEXTUREFORMAT_RGBA32F;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11138. get: function () {
  11139. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11145. get: function () {
  11146. return Engine._TEXTUREFORMAT_RGB;
  11147. },
  11148. enumerable: true,
  11149. configurable: true
  11150. });
  11151. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11152. get: function () {
  11153. return Engine._TEXTUREFORMAT_RGBA;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11159. get: function () {
  11160. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11166. get: function () {
  11167. return Engine._TEXTURETYPE_FLOAT;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11173. get: function () {
  11174. return Engine._TEXTURETYPE_HALF_FLOAT;
  11175. },
  11176. enumerable: true,
  11177. configurable: true
  11178. });
  11179. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11180. get: function () {
  11181. return Engine._SCALEMODE_FLOOR;
  11182. },
  11183. enumerable: true,
  11184. configurable: true
  11185. });
  11186. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11187. get: function () {
  11188. return Engine._SCALEMODE_NEAREST;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11194. get: function () {
  11195. return Engine._SCALEMODE_CEILING;
  11196. },
  11197. enumerable: true,
  11198. configurable: true
  11199. });
  11200. Object.defineProperty(Engine, "Version", {
  11201. get: function () {
  11202. return "3.2.0-beta.3";
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11208. get: function () {
  11209. return this._vrExclusivePointerMode;
  11210. },
  11211. enumerable: true,
  11212. configurable: true
  11213. });
  11214. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11215. get: function () {
  11216. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11222. get: function () {
  11223. return this._webGLVersion < 2 || this.forcePOTTextures;
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. Object.defineProperty(Engine.prototype, "badOS", {
  11229. get: function () {
  11230. return this._badOS;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11236. get: function () {
  11237. return this._badDesktopOS;
  11238. },
  11239. enumerable: true,
  11240. configurable: true
  11241. });
  11242. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11243. get: function () {
  11244. return this._performanceMonitor;
  11245. },
  11246. enumerable: true,
  11247. configurable: true
  11248. });
  11249. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11250. get: function () {
  11251. return this._texturesSupported;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11257. get: function () {
  11258. return this._textureFormatInUse;
  11259. },
  11260. enumerable: true,
  11261. configurable: true
  11262. });
  11263. Object.defineProperty(Engine.prototype, "currentViewport", {
  11264. get: function () {
  11265. return this._cachedViewport;
  11266. },
  11267. enumerable: true,
  11268. configurable: true
  11269. });
  11270. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11271. // Empty texture
  11272. get: function () {
  11273. if (!this._emptyTexture) {
  11274. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11275. }
  11276. return this._emptyTexture;
  11277. },
  11278. enumerable: true,
  11279. configurable: true
  11280. });
  11281. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11282. get: function () {
  11283. if (!this._emptyTexture3D) {
  11284. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11285. }
  11286. return this._emptyTexture3D;
  11287. },
  11288. enumerable: true,
  11289. configurable: true
  11290. });
  11291. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11292. get: function () {
  11293. if (!this._emptyCubeTexture) {
  11294. var faceData = new Uint8Array(4);
  11295. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11296. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11297. }
  11298. return this._emptyCubeTexture;
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. Engine.prototype._rebuildInternalTextures = function () {
  11304. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11305. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11306. var internalTexture = currentState_1[_i];
  11307. internalTexture._rebuild();
  11308. }
  11309. };
  11310. Engine.prototype._rebuildEffects = function () {
  11311. for (var key in this._compiledEffects) {
  11312. var effect = this._compiledEffects[key];
  11313. effect._prepareEffect();
  11314. }
  11315. BABYLON.Effect.ResetCache();
  11316. };
  11317. Engine.prototype._rebuildBuffers = function () {
  11318. // Index / Vertex
  11319. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11320. var scene = _a[_i];
  11321. scene.resetCachedMaterial();
  11322. scene._rebuildGeometries();
  11323. scene._rebuildTextures();
  11324. }
  11325. // Uniforms
  11326. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11327. var uniformBuffer = _c[_b];
  11328. uniformBuffer._rebuild();
  11329. }
  11330. };
  11331. Engine.prototype._initGLContext = function () {
  11332. // Caps
  11333. this._caps = new EngineCapabilities();
  11334. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11335. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11336. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11337. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11338. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11339. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11340. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11341. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11342. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11343. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11344. // Infos
  11345. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11346. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11347. if (rendererInfo != null) {
  11348. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11349. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11350. }
  11351. if (!this._glVendor) {
  11352. this._glVendor = "Unknown vendor";
  11353. }
  11354. if (!this._glRenderer) {
  11355. this._glRenderer = "Unknown renderer";
  11356. }
  11357. // Constants
  11358. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11359. if (this._gl.RGBA16F !== 0x881A) {
  11360. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11361. }
  11362. if (this._gl.RGBA32F !== 0x8814) {
  11363. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11364. }
  11365. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11366. this._gl.DEPTH24_STENCIL8 = 35056;
  11367. }
  11368. // Extensions
  11369. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11370. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11371. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11372. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11373. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11374. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11375. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11376. 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');
  11377. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11378. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11379. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11380. this._caps.highPrecisionShaderSupported = true;
  11381. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11382. if (this._caps.timerQuery) {
  11383. if (this._webGLVersion === 1) {
  11384. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11385. }
  11386. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11387. }
  11388. // Checks if some of the format renders first to allow the use of webgl inspector.
  11389. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11390. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11391. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11392. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11393. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11394. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11395. if (this._webGLVersion > 1) {
  11396. this._gl.HALF_FLOAT_OES = 0x140B;
  11397. }
  11398. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11399. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11400. // Draw buffers
  11401. if (this._webGLVersion > 1) {
  11402. this._caps.drawBuffersExtension = true;
  11403. }
  11404. else {
  11405. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11406. if (drawBuffersExtension !== null) {
  11407. this._caps.drawBuffersExtension = true;
  11408. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11409. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11410. for (var i = 0; i < 16; i++) {
  11411. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11412. }
  11413. }
  11414. else {
  11415. this._caps.drawBuffersExtension = false;
  11416. }
  11417. }
  11418. // Depth Texture
  11419. if (this._webGLVersion > 1) {
  11420. this._caps.depthTextureExtension = true;
  11421. }
  11422. else {
  11423. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11424. if (depthTextureExtension != null) {
  11425. this._caps.depthTextureExtension = true;
  11426. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11427. }
  11428. }
  11429. // Vertex array object
  11430. if (this._webGLVersion > 1) {
  11431. this._caps.vertexArrayObject = true;
  11432. }
  11433. else {
  11434. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11435. if (vertexArrayObjectExtension != null) {
  11436. this._caps.vertexArrayObject = true;
  11437. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11438. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11439. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11440. }
  11441. else {
  11442. this._caps.vertexArrayObject = false;
  11443. }
  11444. }
  11445. // Instances count
  11446. if (this._webGLVersion > 1) {
  11447. this._caps.instancedArrays = true;
  11448. }
  11449. else {
  11450. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11451. if (instanceExtension != null) {
  11452. this._caps.instancedArrays = true;
  11453. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11454. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11455. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11456. }
  11457. else {
  11458. this._caps.instancedArrays = false;
  11459. }
  11460. }
  11461. // Intelligently add supported compressed formats in order to check for.
  11462. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11463. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11464. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11465. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11466. if (this._caps.astc)
  11467. this.texturesSupported.push('-astc.ktx');
  11468. if (this._caps.s3tc)
  11469. this.texturesSupported.push('-dxt.ktx');
  11470. if (this._caps.pvrtc)
  11471. this.texturesSupported.push('-pvrtc.ktx');
  11472. if (this._caps.etc2)
  11473. this.texturesSupported.push('-etc2.ktx');
  11474. if (this._caps.etc1)
  11475. this.texturesSupported.push('-etc1.ktx');
  11476. if (this._gl.getShaderPrecisionFormat) {
  11477. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11478. if (highp) {
  11479. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11480. }
  11481. }
  11482. // Depth buffer
  11483. this.setDepthBuffer(true);
  11484. this.setDepthFunctionToLessOrEqual();
  11485. this.setDepthWrite(true);
  11486. // Texture maps
  11487. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11488. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11489. this._nextFreeTextureSlots.push(slot);
  11490. }
  11491. };
  11492. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11493. get: function () {
  11494. return this._webGLVersion;
  11495. },
  11496. enumerable: true,
  11497. configurable: true
  11498. });
  11499. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11500. /**
  11501. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11502. */
  11503. get: function () {
  11504. return this._isStencilEnable;
  11505. },
  11506. enumerable: true,
  11507. configurable: true
  11508. });
  11509. Engine.prototype._prepareWorkingCanvas = function () {
  11510. if (this._workingCanvas) {
  11511. return;
  11512. }
  11513. this._workingCanvas = document.createElement("canvas");
  11514. var context = this._workingCanvas.getContext("2d");
  11515. if (context) {
  11516. this._workingContext = context;
  11517. }
  11518. };
  11519. Engine.prototype.resetTextureCache = function () {
  11520. for (var key in this._boundTexturesCache) {
  11521. var boundTexture = this._boundTexturesCache[key];
  11522. if (boundTexture) {
  11523. this._removeDesignatedSlot(boundTexture);
  11524. }
  11525. this._boundTexturesCache[key] = null;
  11526. }
  11527. if (!this.disableTextureBindingOptimization) {
  11528. this._nextFreeTextureSlots = [];
  11529. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11530. this._nextFreeTextureSlots.push(slot);
  11531. }
  11532. }
  11533. this._currentTextureChannel = -1;
  11534. };
  11535. Engine.prototype.isDeterministicLockStep = function () {
  11536. return this._deterministicLockstep;
  11537. };
  11538. Engine.prototype.getLockstepMaxSteps = function () {
  11539. return this._lockstepMaxSteps;
  11540. };
  11541. Engine.prototype.getGlInfo = function () {
  11542. return {
  11543. vendor: this._glVendor,
  11544. renderer: this._glRenderer,
  11545. version: this._glVersion
  11546. };
  11547. };
  11548. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11549. if (useScreen === void 0) { useScreen = false; }
  11550. var viewport = camera.viewport;
  11551. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11552. };
  11553. Engine.prototype.getRenderWidth = function (useScreen) {
  11554. if (useScreen === void 0) { useScreen = false; }
  11555. if (!useScreen && this._currentRenderTarget) {
  11556. return this._currentRenderTarget.width;
  11557. }
  11558. return this._gl.drawingBufferWidth;
  11559. };
  11560. Engine.prototype.getRenderHeight = function (useScreen) {
  11561. if (useScreen === void 0) { useScreen = false; }
  11562. if (!useScreen && this._currentRenderTarget) {
  11563. return this._currentRenderTarget.height;
  11564. }
  11565. return this._gl.drawingBufferHeight;
  11566. };
  11567. Engine.prototype.getRenderingCanvas = function () {
  11568. return this._renderingCanvas;
  11569. };
  11570. Engine.prototype.getRenderingCanvasClientRect = function () {
  11571. if (!this._renderingCanvas) {
  11572. return null;
  11573. }
  11574. return this._renderingCanvas.getBoundingClientRect();
  11575. };
  11576. Engine.prototype.setHardwareScalingLevel = function (level) {
  11577. this._hardwareScalingLevel = level;
  11578. this.resize();
  11579. };
  11580. Engine.prototype.getHardwareScalingLevel = function () {
  11581. return this._hardwareScalingLevel;
  11582. };
  11583. Engine.prototype.getLoadedTexturesCache = function () {
  11584. return this._internalTexturesCache;
  11585. };
  11586. Engine.prototype.getCaps = function () {
  11587. return this._caps;
  11588. };
  11589. Object.defineProperty(Engine.prototype, "drawCalls", {
  11590. /** The number of draw calls submitted last frame */
  11591. get: function () {
  11592. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11593. return 0;
  11594. },
  11595. enumerable: true,
  11596. configurable: true
  11597. });
  11598. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11599. get: function () {
  11600. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11601. return null;
  11602. },
  11603. enumerable: true,
  11604. configurable: true
  11605. });
  11606. Engine.prototype.getDepthFunction = function () {
  11607. return this._depthCullingState.depthFunc;
  11608. };
  11609. Engine.prototype.setDepthFunction = function (depthFunc) {
  11610. this._depthCullingState.depthFunc = depthFunc;
  11611. };
  11612. Engine.prototype.setDepthFunctionToGreater = function () {
  11613. this._depthCullingState.depthFunc = this._gl.GREATER;
  11614. };
  11615. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11616. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11617. };
  11618. Engine.prototype.setDepthFunctionToLess = function () {
  11619. this._depthCullingState.depthFunc = this._gl.LESS;
  11620. };
  11621. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11622. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11623. };
  11624. Engine.prototype.getStencilBuffer = function () {
  11625. return this._stencilState.stencilTest;
  11626. };
  11627. Engine.prototype.setStencilBuffer = function (enable) {
  11628. this._stencilState.stencilTest = enable;
  11629. };
  11630. Engine.prototype.getStencilMask = function () {
  11631. return this._stencilState.stencilMask;
  11632. };
  11633. Engine.prototype.setStencilMask = function (mask) {
  11634. this._stencilState.stencilMask = mask;
  11635. };
  11636. Engine.prototype.getStencilFunction = function () {
  11637. return this._stencilState.stencilFunc;
  11638. };
  11639. Engine.prototype.getStencilFunctionReference = function () {
  11640. return this._stencilState.stencilFuncRef;
  11641. };
  11642. Engine.prototype.getStencilFunctionMask = function () {
  11643. return this._stencilState.stencilFuncMask;
  11644. };
  11645. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11646. this._stencilState.stencilFunc = stencilFunc;
  11647. };
  11648. Engine.prototype.setStencilFunctionReference = function (reference) {
  11649. this._stencilState.stencilFuncRef = reference;
  11650. };
  11651. Engine.prototype.setStencilFunctionMask = function (mask) {
  11652. this._stencilState.stencilFuncMask = mask;
  11653. };
  11654. Engine.prototype.getStencilOperationFail = function () {
  11655. return this._stencilState.stencilOpStencilFail;
  11656. };
  11657. Engine.prototype.getStencilOperationDepthFail = function () {
  11658. return this._stencilState.stencilOpDepthFail;
  11659. };
  11660. Engine.prototype.getStencilOperationPass = function () {
  11661. return this._stencilState.stencilOpStencilDepthPass;
  11662. };
  11663. Engine.prototype.setStencilOperationFail = function (operation) {
  11664. this._stencilState.stencilOpStencilFail = operation;
  11665. };
  11666. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11667. this._stencilState.stencilOpDepthFail = operation;
  11668. };
  11669. Engine.prototype.setStencilOperationPass = function (operation) {
  11670. this._stencilState.stencilOpStencilDepthPass = operation;
  11671. };
  11672. Engine.prototype.setDitheringState = function (value) {
  11673. if (value) {
  11674. this._gl.enable(this._gl.DITHER);
  11675. }
  11676. else {
  11677. this._gl.disable(this._gl.DITHER);
  11678. }
  11679. };
  11680. Engine.prototype.setRasterizerState = function (value) {
  11681. if (value) {
  11682. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11683. }
  11684. else {
  11685. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11686. }
  11687. };
  11688. /**
  11689. * stop executing a render loop function and remove it from the execution array
  11690. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11691. */
  11692. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11693. if (!renderFunction) {
  11694. this._activeRenderLoops = [];
  11695. return;
  11696. }
  11697. var index = this._activeRenderLoops.indexOf(renderFunction);
  11698. if (index >= 0) {
  11699. this._activeRenderLoops.splice(index, 1);
  11700. }
  11701. };
  11702. Engine.prototype._renderLoop = function () {
  11703. if (!this._contextWasLost) {
  11704. var shouldRender = true;
  11705. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11706. shouldRender = false;
  11707. }
  11708. if (shouldRender) {
  11709. // Start new frame
  11710. this.beginFrame();
  11711. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11712. var renderFunction = this._activeRenderLoops[index];
  11713. renderFunction();
  11714. }
  11715. // Present
  11716. this.endFrame();
  11717. }
  11718. }
  11719. if (this._activeRenderLoops.length > 0) {
  11720. // Register new frame
  11721. var requester = null;
  11722. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11723. requester = this._vrDisplay;
  11724. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11725. }
  11726. else {
  11727. this._renderingQueueLaunched = false;
  11728. }
  11729. };
  11730. /**
  11731. * Register and execute a render loop. The engine can have more than one render function.
  11732. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11733. * @example
  11734. * engine.runRenderLoop(function () {
  11735. * scene.render()
  11736. * })
  11737. */
  11738. Engine.prototype.runRenderLoop = function (renderFunction) {
  11739. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11740. return;
  11741. }
  11742. this._activeRenderLoops.push(renderFunction);
  11743. if (!this._renderingQueueLaunched) {
  11744. this._renderingQueueLaunched = true;
  11745. this._bindedRenderFunction = this._renderLoop.bind(this);
  11746. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11747. }
  11748. };
  11749. /**
  11750. * Toggle full screen mode.
  11751. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11752. * @param {any} options - an options object to be sent to the requestFullscreen function
  11753. */
  11754. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11755. if (this.isFullscreen) {
  11756. BABYLON.Tools.ExitFullscreen();
  11757. }
  11758. else {
  11759. this._pointerLockRequested = requestPointerLock;
  11760. if (this._renderingCanvas) {
  11761. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11762. }
  11763. }
  11764. };
  11765. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11766. if (stencil === void 0) { stencil = false; }
  11767. this.applyStates();
  11768. var mode = 0;
  11769. if (backBuffer && color) {
  11770. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11771. mode |= this._gl.COLOR_BUFFER_BIT;
  11772. }
  11773. if (depth) {
  11774. this._gl.clearDepth(1.0);
  11775. mode |= this._gl.DEPTH_BUFFER_BIT;
  11776. }
  11777. if (stencil) {
  11778. this._gl.clearStencil(0);
  11779. mode |= this._gl.STENCIL_BUFFER_BIT;
  11780. }
  11781. this._gl.clear(mode);
  11782. };
  11783. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11784. var gl = this._gl;
  11785. // Save state
  11786. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11787. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11788. // Change state
  11789. gl.enable(gl.SCISSOR_TEST);
  11790. gl.scissor(x, y, width, height);
  11791. // Clear
  11792. this.clear(clearColor, true, true, true);
  11793. // Restore state
  11794. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11795. if (curScissor === true) {
  11796. gl.enable(gl.SCISSOR_TEST);
  11797. }
  11798. else {
  11799. gl.disable(gl.SCISSOR_TEST);
  11800. }
  11801. };
  11802. /**
  11803. * Set the WebGL's viewport
  11804. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11805. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11806. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11807. */
  11808. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11809. var width = requiredWidth || this.getRenderWidth();
  11810. var height = requiredHeight || this.getRenderHeight();
  11811. var x = viewport.x || 0;
  11812. var y = viewport.y || 0;
  11813. this._cachedViewport = viewport;
  11814. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11815. };
  11816. /**
  11817. * Directly set the WebGL Viewport
  11818. * The x, y, width & height are directly passed to the WebGL call
  11819. * @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.
  11820. */
  11821. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11822. var currentViewport = this._cachedViewport;
  11823. this._cachedViewport = null;
  11824. this._gl.viewport(x, y, width, height);
  11825. return currentViewport;
  11826. };
  11827. Engine.prototype.beginFrame = function () {
  11828. this.onBeginFrameObservable.notifyObservers(this);
  11829. this._measureFps();
  11830. };
  11831. Engine.prototype.endFrame = function () {
  11832. //force a flush in case we are using a bad OS.
  11833. if (this._badOS) {
  11834. this.flushFramebuffer();
  11835. }
  11836. //submit frame to the vr device, if enabled
  11837. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11838. // TODO: We should only submit the frame if we read frameData successfully.
  11839. this._vrDisplay.submitFrame();
  11840. }
  11841. this.onEndFrameObservable.notifyObservers(this);
  11842. };
  11843. /**
  11844. * resize the view according to the canvas' size.
  11845. * @example
  11846. * window.addEventListener("resize", function () {
  11847. * engine.resize();
  11848. * });
  11849. */
  11850. Engine.prototype.resize = function () {
  11851. // We're not resizing the size of the canvas while in VR mode & presenting
  11852. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11853. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11854. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11855. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11856. }
  11857. };
  11858. /**
  11859. * force a specific size of the canvas
  11860. * @param {number} width - the new canvas' width
  11861. * @param {number} height - the new canvas' height
  11862. */
  11863. Engine.prototype.setSize = function (width, height) {
  11864. if (!this._renderingCanvas) {
  11865. return;
  11866. }
  11867. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11868. return;
  11869. }
  11870. this._renderingCanvas.width = width;
  11871. this._renderingCanvas.height = height;
  11872. for (var index = 0; index < this.scenes.length; index++) {
  11873. var scene = this.scenes[index];
  11874. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11875. var cam = scene.cameras[camIndex];
  11876. cam._currentRenderId = 0;
  11877. }
  11878. }
  11879. if (this.onResizeObservable.hasObservers) {
  11880. this.onResizeObservable.notifyObservers(this);
  11881. }
  11882. };
  11883. // WebVR functions
  11884. Engine.prototype.isVRDevicePresent = function () {
  11885. return !!this._vrDisplay;
  11886. };
  11887. Engine.prototype.getVRDevice = function () {
  11888. return this._vrDisplay;
  11889. };
  11890. /**
  11891. * Initializes a webVR display and starts listening to display change events.
  11892. * The onVRDisplayChangedObservable will be notified upon these changes.
  11893. * @returns The onVRDisplayChangedObservable.
  11894. */
  11895. Engine.prototype.initWebVR = function () {
  11896. this.initWebVRAsync();
  11897. return this.onVRDisplayChangedObservable;
  11898. };
  11899. /**
  11900. * Initializes a webVR display and starts listening to display change events.
  11901. * The onVRDisplayChangedObservable will be notified upon these changes.
  11902. * @returns A promise containing a VRDisplay and if vr is supported.
  11903. */
  11904. Engine.prototype.initWebVRAsync = function () {
  11905. var _this = this;
  11906. var notifyObservers = function () {
  11907. var eventArgs = {
  11908. vrDisplay: _this._vrDisplay,
  11909. vrSupported: _this._vrSupported
  11910. };
  11911. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11912. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11913. };
  11914. if (!this._onVrDisplayConnect) {
  11915. this._onVrDisplayConnect = function (event) {
  11916. _this._vrDisplay = event.display;
  11917. notifyObservers();
  11918. };
  11919. this._onVrDisplayDisconnect = function () {
  11920. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11921. _this._vrDisplay = undefined;
  11922. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11923. notifyObservers();
  11924. };
  11925. this._onVrDisplayPresentChange = function () {
  11926. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11927. };
  11928. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11929. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11930. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11931. }
  11932. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11933. this._webVRInitPromise.then(notifyObservers);
  11934. return this._webVRInitPromise;
  11935. };
  11936. Engine.prototype.enableVR = function () {
  11937. var _this = this;
  11938. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11939. var onResolved = function () {
  11940. _this.onVRRequestPresentComplete.notifyObservers(true);
  11941. _this._onVRFullScreenTriggered();
  11942. };
  11943. var onRejected = function () {
  11944. _this.onVRRequestPresentComplete.notifyObservers(false);
  11945. };
  11946. this.onVRRequestPresentStart.notifyObservers(this);
  11947. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11948. }
  11949. };
  11950. Engine.prototype.disableVR = function () {
  11951. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11952. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11953. }
  11954. };
  11955. Engine.prototype._getVRDisplaysAsync = function () {
  11956. var _this = this;
  11957. return new Promise(function (res, rej) {
  11958. if (navigator.getVRDisplays) {
  11959. navigator.getVRDisplays().then(function (devices) {
  11960. _this._vrSupported = true;
  11961. // note that devices may actually be an empty array. This is fine;
  11962. // we expect this._vrDisplay to be undefined in this case.
  11963. _this._vrDisplay = devices[0];
  11964. res({
  11965. vrDisplay: _this._vrDisplay,
  11966. vrSupported: _this._vrSupported
  11967. });
  11968. });
  11969. }
  11970. else {
  11971. _this._vrDisplay = undefined;
  11972. _this._vrSupported = false;
  11973. res({
  11974. vrDisplay: _this._vrDisplay,
  11975. vrSupported: _this._vrSupported
  11976. });
  11977. }
  11978. });
  11979. };
  11980. /**
  11981. * Binds the frame buffer to the specified texture.
  11982. * @param texture The texture to render to or null for the default canvas
  11983. * @param faceIndex The face of the texture to render to in case of cube texture
  11984. * @param requiredWidth The width of the target to render to
  11985. * @param requiredHeight The height of the target to render to
  11986. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11987. * @param depthStencilTexture The depth stencil texture to use to render
  11988. */
  11989. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11990. if (this._currentRenderTarget) {
  11991. this.unBindFramebuffer(this._currentRenderTarget);
  11992. }
  11993. this._currentRenderTarget = texture;
  11994. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11995. var gl = this._gl;
  11996. if (texture.isCube) {
  11997. if (faceIndex === undefined) {
  11998. faceIndex = 0;
  11999. }
  12000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12001. if (depthStencilTexture) {
  12002. if (depthStencilTexture._generateStencilBuffer) {
  12003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12004. }
  12005. else {
  12006. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12007. }
  12008. }
  12009. }
  12010. if (this._cachedViewport && !forceFullscreenViewport) {
  12011. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12012. }
  12013. else {
  12014. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12015. }
  12016. this.wipeCaches();
  12017. };
  12018. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12019. if (this._currentFramebuffer !== framebuffer) {
  12020. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12021. this._currentFramebuffer = framebuffer;
  12022. }
  12023. };
  12024. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12025. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12026. this._currentRenderTarget = null;
  12027. // If MSAA, we need to bitblt back to main texture
  12028. var gl = this._gl;
  12029. if (texture._MSAAFramebuffer) {
  12030. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12031. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12032. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12033. }
  12034. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12035. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12036. gl.generateMipmap(gl.TEXTURE_2D);
  12037. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12038. }
  12039. if (onBeforeUnbind) {
  12040. if (texture._MSAAFramebuffer) {
  12041. // Bind the correct framebuffer
  12042. this.bindUnboundFramebuffer(texture._framebuffer);
  12043. }
  12044. onBeforeUnbind();
  12045. }
  12046. this.bindUnboundFramebuffer(null);
  12047. };
  12048. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12049. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12050. this._currentRenderTarget = null;
  12051. // If MSAA, we need to bitblt back to main texture
  12052. var gl = this._gl;
  12053. if (textures[0]._MSAAFramebuffer) {
  12054. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12055. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12056. var attachments = textures[0]._attachments;
  12057. if (!attachments) {
  12058. attachments = new Array(textures.length);
  12059. textures[0]._attachments = attachments;
  12060. }
  12061. for (var i = 0; i < textures.length; i++) {
  12062. var texture = textures[i];
  12063. for (var j = 0; j < attachments.length; j++) {
  12064. attachments[j] = gl.NONE;
  12065. }
  12066. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12067. gl.readBuffer(attachments[i]);
  12068. gl.drawBuffers(attachments);
  12069. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12070. }
  12071. for (var i = 0; i < attachments.length; i++) {
  12072. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12073. }
  12074. gl.drawBuffers(attachments);
  12075. }
  12076. for (var i = 0; i < textures.length; i++) {
  12077. var texture = textures[i];
  12078. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12079. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12080. gl.generateMipmap(gl.TEXTURE_2D);
  12081. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12082. }
  12083. }
  12084. if (onBeforeUnbind) {
  12085. if (textures[0]._MSAAFramebuffer) {
  12086. // Bind the correct framebuffer
  12087. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12088. }
  12089. onBeforeUnbind();
  12090. }
  12091. this.bindUnboundFramebuffer(null);
  12092. };
  12093. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12094. if (texture.generateMipMaps) {
  12095. var gl = this._gl;
  12096. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12097. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12098. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12099. }
  12100. };
  12101. Engine.prototype.flushFramebuffer = function () {
  12102. this._gl.flush();
  12103. };
  12104. Engine.prototype.restoreDefaultFramebuffer = function () {
  12105. if (this._currentRenderTarget) {
  12106. this.unBindFramebuffer(this._currentRenderTarget);
  12107. }
  12108. else {
  12109. this.bindUnboundFramebuffer(null);
  12110. }
  12111. if (this._cachedViewport) {
  12112. this.setViewport(this._cachedViewport);
  12113. }
  12114. this.wipeCaches();
  12115. };
  12116. // UBOs
  12117. Engine.prototype.createUniformBuffer = function (elements) {
  12118. var ubo = this._gl.createBuffer();
  12119. if (!ubo) {
  12120. throw new Error("Unable to create uniform buffer");
  12121. }
  12122. this.bindUniformBuffer(ubo);
  12123. if (elements instanceof Float32Array) {
  12124. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12125. }
  12126. else {
  12127. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12128. }
  12129. this.bindUniformBuffer(null);
  12130. ubo.references = 1;
  12131. return ubo;
  12132. };
  12133. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12134. var ubo = this._gl.createBuffer();
  12135. if (!ubo) {
  12136. throw new Error("Unable to create dynamic uniform buffer");
  12137. }
  12138. this.bindUniformBuffer(ubo);
  12139. if (elements instanceof Float32Array) {
  12140. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12141. }
  12142. else {
  12143. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12144. }
  12145. this.bindUniformBuffer(null);
  12146. ubo.references = 1;
  12147. return ubo;
  12148. };
  12149. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12150. this.bindUniformBuffer(uniformBuffer);
  12151. if (offset === undefined) {
  12152. offset = 0;
  12153. }
  12154. if (count === undefined) {
  12155. if (elements instanceof Float32Array) {
  12156. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12157. }
  12158. else {
  12159. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12160. }
  12161. }
  12162. else {
  12163. if (elements instanceof Float32Array) {
  12164. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12165. }
  12166. else {
  12167. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12168. }
  12169. }
  12170. this.bindUniformBuffer(null);
  12171. };
  12172. // VBOs
  12173. Engine.prototype._resetVertexBufferBinding = function () {
  12174. this.bindArrayBuffer(null);
  12175. this._cachedVertexBuffers = null;
  12176. };
  12177. /**
  12178. * Creates a vertex buffer
  12179. * @param data the data for the vertex buffer
  12180. * @returns the new WebGL static buffer
  12181. */
  12182. Engine.prototype.createVertexBuffer = function (data) {
  12183. var vbo = this._gl.createBuffer();
  12184. if (!vbo) {
  12185. throw new Error("Unable to create vertex buffer");
  12186. }
  12187. this.bindArrayBuffer(vbo);
  12188. if (data instanceof Array) {
  12189. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12190. }
  12191. else {
  12192. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12193. }
  12194. this._resetVertexBufferBinding();
  12195. vbo.references = 1;
  12196. return vbo;
  12197. };
  12198. /**
  12199. * Creates a dynamic vertex buffer
  12200. * @param data the data for the dynamic vertex buffer
  12201. * @returns the new WebGL dynamic buffer
  12202. */
  12203. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12204. var vbo = this._gl.createBuffer();
  12205. if (!vbo) {
  12206. throw new Error("Unable to create dynamic vertex buffer");
  12207. }
  12208. this.bindArrayBuffer(vbo);
  12209. if (data instanceof Array) {
  12210. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12211. }
  12212. else {
  12213. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12214. }
  12215. this._resetVertexBufferBinding();
  12216. vbo.references = 1;
  12217. return vbo;
  12218. };
  12219. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12220. if (offset === void 0) { offset = 0; }
  12221. // Force cache update
  12222. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12223. this.bindIndexBuffer(indexBuffer);
  12224. var arrayBuffer;
  12225. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12226. arrayBuffer = indices;
  12227. }
  12228. else {
  12229. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12230. }
  12231. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12232. this._resetIndexBufferBinding();
  12233. };
  12234. /**
  12235. * Updates a dynamic vertex buffer.
  12236. * @param vertexBuffer the vertex buffer to update
  12237. * @param data the data used to update the vertex buffer
  12238. * @param byteOffset the byte offset of the data (optional)
  12239. * @param byteLength the byte length of the data (optional)
  12240. */
  12241. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12242. this.bindArrayBuffer(vertexBuffer);
  12243. if (byteOffset === undefined) {
  12244. byteOffset = 0;
  12245. }
  12246. if (byteLength === undefined) {
  12247. if (data instanceof Array) {
  12248. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12249. }
  12250. else {
  12251. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12252. }
  12253. }
  12254. else {
  12255. if (data instanceof Array) {
  12256. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12257. }
  12258. else {
  12259. if (data instanceof ArrayBuffer) {
  12260. data = new Uint8Array(data, byteOffset, byteLength);
  12261. }
  12262. else {
  12263. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12264. }
  12265. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12266. }
  12267. }
  12268. this._resetVertexBufferBinding();
  12269. };
  12270. Engine.prototype._resetIndexBufferBinding = function () {
  12271. this.bindIndexBuffer(null);
  12272. this._cachedIndexBuffer = null;
  12273. };
  12274. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12275. var vbo = this._gl.createBuffer();
  12276. if (!vbo) {
  12277. throw new Error("Unable to create index buffer");
  12278. }
  12279. this.bindIndexBuffer(vbo);
  12280. // Check for 32 bits indices
  12281. var arrayBuffer;
  12282. var need32Bits = false;
  12283. if (indices instanceof Uint16Array) {
  12284. arrayBuffer = indices;
  12285. }
  12286. else {
  12287. //check 32 bit support
  12288. if (this._caps.uintIndices) {
  12289. if (indices instanceof Uint32Array) {
  12290. arrayBuffer = indices;
  12291. need32Bits = true;
  12292. }
  12293. else {
  12294. //number[] or Int32Array, check if 32 bit is necessary
  12295. for (var index = 0; index < indices.length; index++) {
  12296. if (indices[index] > 65535) {
  12297. need32Bits = true;
  12298. break;
  12299. }
  12300. }
  12301. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12302. }
  12303. }
  12304. else {
  12305. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12306. arrayBuffer = new Uint16Array(indices);
  12307. }
  12308. }
  12309. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12310. this._resetIndexBufferBinding();
  12311. vbo.references = 1;
  12312. vbo.is32Bits = need32Bits;
  12313. return vbo;
  12314. };
  12315. Engine.prototype.bindArrayBuffer = function (buffer) {
  12316. if (!this._vaoRecordInProgress) {
  12317. this._unbindVertexArrayObject();
  12318. }
  12319. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12320. };
  12321. Engine.prototype.bindUniformBuffer = function (buffer) {
  12322. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12323. };
  12324. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12325. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12326. };
  12327. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12328. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12329. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12330. };
  12331. ;
  12332. Engine.prototype.bindIndexBuffer = function (buffer) {
  12333. if (!this._vaoRecordInProgress) {
  12334. this._unbindVertexArrayObject();
  12335. }
  12336. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12337. };
  12338. Engine.prototype.bindBuffer = function (buffer, target) {
  12339. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12340. this._gl.bindBuffer(target, buffer);
  12341. this._currentBoundBuffer[target] = buffer;
  12342. }
  12343. };
  12344. Engine.prototype.updateArrayBuffer = function (data) {
  12345. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12346. };
  12347. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12348. var pointer = this._currentBufferPointers[indx];
  12349. var changed = false;
  12350. if (!pointer.active) {
  12351. changed = true;
  12352. pointer.active = true;
  12353. pointer.index = indx;
  12354. pointer.size = size;
  12355. pointer.type = type;
  12356. pointer.normalized = normalized;
  12357. pointer.stride = stride;
  12358. pointer.offset = offset;
  12359. pointer.buffer = buffer;
  12360. }
  12361. else {
  12362. if (pointer.buffer !== buffer) {
  12363. pointer.buffer = buffer;
  12364. changed = true;
  12365. }
  12366. if (pointer.size !== size) {
  12367. pointer.size = size;
  12368. changed = true;
  12369. }
  12370. if (pointer.type !== type) {
  12371. pointer.type = type;
  12372. changed = true;
  12373. }
  12374. if (pointer.normalized !== normalized) {
  12375. pointer.normalized = normalized;
  12376. changed = true;
  12377. }
  12378. if (pointer.stride !== stride) {
  12379. pointer.stride = stride;
  12380. changed = true;
  12381. }
  12382. if (pointer.offset !== offset) {
  12383. pointer.offset = offset;
  12384. changed = true;
  12385. }
  12386. }
  12387. if (changed || this._vaoRecordInProgress) {
  12388. this.bindArrayBuffer(buffer);
  12389. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12390. }
  12391. };
  12392. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12393. if (indexBuffer == null) {
  12394. return;
  12395. }
  12396. if (this._cachedIndexBuffer !== indexBuffer) {
  12397. this._cachedIndexBuffer = indexBuffer;
  12398. this.bindIndexBuffer(indexBuffer);
  12399. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12400. }
  12401. };
  12402. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12403. var attributes = effect.getAttributesNames();
  12404. if (!this._vaoRecordInProgress) {
  12405. this._unbindVertexArrayObject();
  12406. }
  12407. this.unbindAllAttributes();
  12408. for (var index = 0; index < attributes.length; index++) {
  12409. var order = effect.getAttributeLocation(index);
  12410. if (order >= 0) {
  12411. var vertexBuffer = vertexBuffers[attributes[index]];
  12412. if (!vertexBuffer) {
  12413. continue;
  12414. }
  12415. this._gl.enableVertexAttribArray(order);
  12416. if (!this._vaoRecordInProgress) {
  12417. this._vertexAttribArraysEnabled[order] = true;
  12418. }
  12419. var buffer = vertexBuffer.getBuffer();
  12420. if (buffer) {
  12421. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  12422. if (vertexBuffer.getIsInstanced()) {
  12423. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12424. if (!this._vaoRecordInProgress) {
  12425. this._currentInstanceLocations.push(order);
  12426. this._currentInstanceBuffers.push(buffer);
  12427. }
  12428. }
  12429. }
  12430. }
  12431. }
  12432. };
  12433. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12434. var vao = this._gl.createVertexArray();
  12435. this._vaoRecordInProgress = true;
  12436. this._gl.bindVertexArray(vao);
  12437. this._mustWipeVertexAttributes = true;
  12438. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12439. this.bindIndexBuffer(indexBuffer);
  12440. this._vaoRecordInProgress = false;
  12441. this._gl.bindVertexArray(null);
  12442. return vao;
  12443. };
  12444. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12445. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12446. this._cachedVertexArrayObject = vertexArrayObject;
  12447. this._gl.bindVertexArray(vertexArrayObject);
  12448. this._cachedVertexBuffers = null;
  12449. this._cachedIndexBuffer = null;
  12450. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12451. this._mustWipeVertexAttributes = true;
  12452. }
  12453. };
  12454. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12455. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12456. this._cachedVertexBuffers = vertexBuffer;
  12457. this._cachedEffectForVertexBuffers = effect;
  12458. var attributesCount = effect.getAttributesCount();
  12459. this._unbindVertexArrayObject();
  12460. this.unbindAllAttributes();
  12461. var offset = 0;
  12462. for (var index = 0; index < attributesCount; index++) {
  12463. if (index < vertexDeclaration.length) {
  12464. var order = effect.getAttributeLocation(index);
  12465. if (order >= 0) {
  12466. this._gl.enableVertexAttribArray(order);
  12467. this._vertexAttribArraysEnabled[order] = true;
  12468. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12469. }
  12470. offset += vertexDeclaration[index] * 4;
  12471. }
  12472. }
  12473. }
  12474. this._bindIndexBufferWithCache(indexBuffer);
  12475. };
  12476. Engine.prototype._unbindVertexArrayObject = function () {
  12477. if (!this._cachedVertexArrayObject) {
  12478. return;
  12479. }
  12480. this._cachedVertexArrayObject = null;
  12481. this._gl.bindVertexArray(null);
  12482. };
  12483. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12484. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12485. this._cachedVertexBuffers = vertexBuffers;
  12486. this._cachedEffectForVertexBuffers = effect;
  12487. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12488. }
  12489. this._bindIndexBufferWithCache(indexBuffer);
  12490. };
  12491. Engine.prototype.unbindInstanceAttributes = function () {
  12492. var boundBuffer;
  12493. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12494. var instancesBuffer = this._currentInstanceBuffers[i];
  12495. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12496. boundBuffer = instancesBuffer;
  12497. this.bindArrayBuffer(instancesBuffer);
  12498. }
  12499. var offsetLocation = this._currentInstanceLocations[i];
  12500. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12501. }
  12502. this._currentInstanceBuffers.length = 0;
  12503. this._currentInstanceLocations.length = 0;
  12504. };
  12505. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12506. this._gl.deleteVertexArray(vao);
  12507. };
  12508. Engine.prototype._releaseBuffer = function (buffer) {
  12509. buffer.references--;
  12510. if (buffer.references === 0) {
  12511. this._gl.deleteBuffer(buffer);
  12512. return true;
  12513. }
  12514. return false;
  12515. };
  12516. Engine.prototype.createInstancesBuffer = function (capacity) {
  12517. var buffer = this._gl.createBuffer();
  12518. if (!buffer) {
  12519. throw new Error("Unable to create instance buffer");
  12520. }
  12521. buffer.capacity = capacity;
  12522. this.bindArrayBuffer(buffer);
  12523. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12524. return buffer;
  12525. };
  12526. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12527. this._gl.deleteBuffer(buffer);
  12528. };
  12529. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12530. this.bindArrayBuffer(instancesBuffer);
  12531. if (data) {
  12532. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12533. }
  12534. if (offsetLocations[0].index !== undefined) {
  12535. var stride = 0;
  12536. for (var i = 0; i < offsetLocations.length; i++) {
  12537. var ai = offsetLocations[i];
  12538. stride += ai.attributeSize * 4;
  12539. }
  12540. for (var i = 0; i < offsetLocations.length; i++) {
  12541. var ai = offsetLocations[i];
  12542. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12543. this._gl.enableVertexAttribArray(ai.index);
  12544. this._vertexAttribArraysEnabled[ai.index] = true;
  12545. }
  12546. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12547. this._gl.vertexAttribDivisor(ai.index, 1);
  12548. this._currentInstanceLocations.push(ai.index);
  12549. this._currentInstanceBuffers.push(instancesBuffer);
  12550. }
  12551. }
  12552. else {
  12553. for (var index = 0; index < 4; index++) {
  12554. var offsetLocation = offsetLocations[index];
  12555. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12556. this._gl.enableVertexAttribArray(offsetLocation);
  12557. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12558. }
  12559. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12560. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12561. this._currentInstanceLocations.push(offsetLocation);
  12562. this._currentInstanceBuffers.push(instancesBuffer);
  12563. }
  12564. }
  12565. };
  12566. Engine.prototype.applyStates = function () {
  12567. this._depthCullingState.apply(this._gl);
  12568. this._stencilState.apply(this._gl);
  12569. this._alphaState.apply(this._gl);
  12570. };
  12571. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12572. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12573. };
  12574. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12575. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12576. };
  12577. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12578. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12579. };
  12580. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12581. // Apply states
  12582. this.applyStates();
  12583. this._drawCalls.addCount(1, false);
  12584. // Render
  12585. var drawMode = this._drawMode(fillMode);
  12586. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12587. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12588. if (instancesCount) {
  12589. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12590. }
  12591. else {
  12592. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12593. }
  12594. };
  12595. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12596. // Apply states
  12597. this.applyStates();
  12598. this._drawCalls.addCount(1, false);
  12599. var drawMode = this._drawMode(fillMode);
  12600. if (instancesCount) {
  12601. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12602. }
  12603. else {
  12604. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12605. }
  12606. };
  12607. Engine.prototype._drawMode = function (fillMode) {
  12608. switch (fillMode) {
  12609. // Triangle views
  12610. case BABYLON.Material.TriangleFillMode:
  12611. return this._gl.TRIANGLES;
  12612. case BABYLON.Material.PointFillMode:
  12613. return this._gl.POINTS;
  12614. case BABYLON.Material.WireFrameFillMode:
  12615. return this._gl.LINES;
  12616. // Draw modes
  12617. case BABYLON.Material.PointListDrawMode:
  12618. return this._gl.POINTS;
  12619. case BABYLON.Material.LineListDrawMode:
  12620. return this._gl.LINES;
  12621. case BABYLON.Material.LineLoopDrawMode:
  12622. return this._gl.LINE_LOOP;
  12623. case BABYLON.Material.LineStripDrawMode:
  12624. return this._gl.LINE_STRIP;
  12625. case BABYLON.Material.TriangleStripDrawMode:
  12626. return this._gl.TRIANGLE_STRIP;
  12627. case BABYLON.Material.TriangleFanDrawMode:
  12628. return this._gl.TRIANGLE_FAN;
  12629. default:
  12630. return this._gl.TRIANGLES;
  12631. }
  12632. };
  12633. // Shaders
  12634. Engine.prototype._releaseEffect = function (effect) {
  12635. if (this._compiledEffects[effect._key]) {
  12636. delete this._compiledEffects[effect._key];
  12637. this._deleteProgram(effect.getProgram());
  12638. }
  12639. };
  12640. Engine.prototype._deleteProgram = function (program) {
  12641. if (program) {
  12642. program.__SPECTOR_rebuildProgram = null;
  12643. if (program.transformFeedback) {
  12644. this.deleteTransformFeedback(program.transformFeedback);
  12645. program.transformFeedback = null;
  12646. }
  12647. this._gl.deleteProgram(program);
  12648. }
  12649. };
  12650. /**
  12651. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12652. * @param samplers An array of string used to represent textures
  12653. */
  12654. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12655. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12656. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12657. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12658. if (this._compiledEffects[name]) {
  12659. var compiledEffect = this._compiledEffects[name];
  12660. if (onCompiled && compiledEffect.isReady()) {
  12661. onCompiled(compiledEffect);
  12662. }
  12663. return compiledEffect;
  12664. }
  12665. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12666. effect._key = name;
  12667. this._compiledEffects[name] = effect;
  12668. return effect;
  12669. };
  12670. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12671. if (uniformsNames === void 0) { uniformsNames = []; }
  12672. if (samplers === void 0) { samplers = []; }
  12673. if (defines === void 0) { defines = ""; }
  12674. return this.createEffect({
  12675. vertex: "particles",
  12676. fragmentElement: fragmentName
  12677. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12678. };
  12679. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12680. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12681. context = context || this._gl;
  12682. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12683. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12684. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12685. };
  12686. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12687. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12688. context = context || this._gl;
  12689. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12690. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12691. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12692. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12693. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12694. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12695. return program;
  12696. };
  12697. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12698. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12699. var shaderProgram = context.createProgram();
  12700. if (!shaderProgram) {
  12701. throw new Error("Unable to create program");
  12702. }
  12703. context.attachShader(shaderProgram, vertexShader);
  12704. context.attachShader(shaderProgram, fragmentShader);
  12705. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12706. var transformFeedback = this.createTransformFeedback();
  12707. this.bindTransformFeedback(transformFeedback);
  12708. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12709. shaderProgram.transformFeedback = transformFeedback;
  12710. }
  12711. context.linkProgram(shaderProgram);
  12712. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12713. this.bindTransformFeedback(null);
  12714. }
  12715. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12716. if (!linked) {
  12717. context.validateProgram(shaderProgram);
  12718. var error = context.getProgramInfoLog(shaderProgram);
  12719. if (error) {
  12720. throw new Error(error);
  12721. }
  12722. }
  12723. context.deleteShader(vertexShader);
  12724. context.deleteShader(fragmentShader);
  12725. return shaderProgram;
  12726. };
  12727. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12728. var results = new Array();
  12729. for (var index = 0; index < uniformsNames.length; index++) {
  12730. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12731. }
  12732. return results;
  12733. };
  12734. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12735. var results = [];
  12736. for (var index = 0; index < attributesNames.length; index++) {
  12737. try {
  12738. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12739. }
  12740. catch (e) {
  12741. results.push(-1);
  12742. }
  12743. }
  12744. return results;
  12745. };
  12746. Engine.prototype.enableEffect = function (effect) {
  12747. if (!effect) {
  12748. return;
  12749. }
  12750. // Use program
  12751. this.bindSamplers(effect);
  12752. this._currentEffect = effect;
  12753. if (effect.onBind) {
  12754. effect.onBind(effect);
  12755. }
  12756. effect.onBindObservable.notifyObservers(effect);
  12757. };
  12758. Engine.prototype.setIntArray = function (uniform, array) {
  12759. if (!uniform)
  12760. return;
  12761. this._gl.uniform1iv(uniform, array);
  12762. };
  12763. Engine.prototype.setIntArray2 = function (uniform, array) {
  12764. if (!uniform || array.length % 2 !== 0)
  12765. return;
  12766. this._gl.uniform2iv(uniform, array);
  12767. };
  12768. Engine.prototype.setIntArray3 = function (uniform, array) {
  12769. if (!uniform || array.length % 3 !== 0)
  12770. return;
  12771. this._gl.uniform3iv(uniform, array);
  12772. };
  12773. Engine.prototype.setIntArray4 = function (uniform, array) {
  12774. if (!uniform || array.length % 4 !== 0)
  12775. return;
  12776. this._gl.uniform4iv(uniform, array);
  12777. };
  12778. Engine.prototype.setFloatArray = function (uniform, array) {
  12779. if (!uniform)
  12780. return;
  12781. this._gl.uniform1fv(uniform, array);
  12782. };
  12783. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12784. if (!uniform || array.length % 2 !== 0)
  12785. return;
  12786. this._gl.uniform2fv(uniform, array);
  12787. };
  12788. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12789. if (!uniform || array.length % 3 !== 0)
  12790. return;
  12791. this._gl.uniform3fv(uniform, array);
  12792. };
  12793. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12794. if (!uniform || array.length % 4 !== 0)
  12795. return;
  12796. this._gl.uniform4fv(uniform, array);
  12797. };
  12798. Engine.prototype.setArray = function (uniform, array) {
  12799. if (!uniform)
  12800. return;
  12801. this._gl.uniform1fv(uniform, array);
  12802. };
  12803. Engine.prototype.setArray2 = function (uniform, array) {
  12804. if (!uniform || array.length % 2 !== 0)
  12805. return;
  12806. this._gl.uniform2fv(uniform, array);
  12807. };
  12808. Engine.prototype.setArray3 = function (uniform, array) {
  12809. if (!uniform || array.length % 3 !== 0)
  12810. return;
  12811. this._gl.uniform3fv(uniform, array);
  12812. };
  12813. Engine.prototype.setArray4 = function (uniform, array) {
  12814. if (!uniform || array.length % 4 !== 0)
  12815. return;
  12816. this._gl.uniform4fv(uniform, array);
  12817. };
  12818. Engine.prototype.setMatrices = function (uniform, matrices) {
  12819. if (!uniform)
  12820. return;
  12821. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12822. };
  12823. Engine.prototype.setMatrix = function (uniform, matrix) {
  12824. if (!uniform)
  12825. return;
  12826. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12827. };
  12828. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12829. if (!uniform)
  12830. return;
  12831. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12832. };
  12833. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12834. if (!uniform)
  12835. return;
  12836. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12837. };
  12838. Engine.prototype.setInt = function (uniform, value) {
  12839. if (!uniform)
  12840. return;
  12841. this._gl.uniform1i(uniform, value);
  12842. };
  12843. Engine.prototype.setFloat = function (uniform, value) {
  12844. if (!uniform)
  12845. return;
  12846. this._gl.uniform1f(uniform, value);
  12847. };
  12848. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12849. if (!uniform)
  12850. return;
  12851. this._gl.uniform2f(uniform, x, y);
  12852. };
  12853. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12854. if (!uniform)
  12855. return;
  12856. this._gl.uniform3f(uniform, x, y, z);
  12857. };
  12858. Engine.prototype.setBool = function (uniform, bool) {
  12859. if (!uniform)
  12860. return;
  12861. this._gl.uniform1i(uniform, bool);
  12862. };
  12863. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12864. if (!uniform)
  12865. return;
  12866. this._gl.uniform4f(uniform, x, y, z, w);
  12867. };
  12868. Engine.prototype.setColor3 = function (uniform, color3) {
  12869. if (!uniform)
  12870. return;
  12871. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12872. };
  12873. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12874. if (!uniform)
  12875. return;
  12876. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12877. };
  12878. /**
  12879. * Sets a Color4 on a uniform variable
  12880. * @param uniform defines the uniform location
  12881. * @param color4 defines the value to be set
  12882. */
  12883. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12884. if (!uniform)
  12885. return;
  12886. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12887. };
  12888. // States
  12889. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12890. if (zOffset === void 0) { zOffset = 0; }
  12891. if (reverseSide === void 0) { reverseSide = false; }
  12892. // Culling
  12893. if (this._depthCullingState.cull !== culling || force) {
  12894. this._depthCullingState.cull = culling;
  12895. }
  12896. // Cull face
  12897. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12898. if (this._depthCullingState.cullFace !== cullFace || force) {
  12899. this._depthCullingState.cullFace = cullFace;
  12900. }
  12901. // Z offset
  12902. this.setZOffset(zOffset);
  12903. // Front face
  12904. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12905. if (this._depthCullingState.frontFace !== frontFace || force) {
  12906. this._depthCullingState.frontFace = frontFace;
  12907. }
  12908. };
  12909. Engine.prototype.setZOffset = function (value) {
  12910. this._depthCullingState.zOffset = value;
  12911. };
  12912. Engine.prototype.getZOffset = function () {
  12913. return this._depthCullingState.zOffset;
  12914. };
  12915. Engine.prototype.setDepthBuffer = function (enable) {
  12916. this._depthCullingState.depthTest = enable;
  12917. };
  12918. Engine.prototype.getDepthWrite = function () {
  12919. return this._depthCullingState.depthMask;
  12920. };
  12921. Engine.prototype.setDepthWrite = function (enable) {
  12922. this._depthCullingState.depthMask = enable;
  12923. };
  12924. Engine.prototype.setColorWrite = function (enable) {
  12925. this._gl.colorMask(enable, enable, enable, enable);
  12926. this._colorWrite = enable;
  12927. };
  12928. Engine.prototype.getColorWrite = function () {
  12929. return this._colorWrite;
  12930. };
  12931. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12932. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12933. };
  12934. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12935. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12936. if (this._alphaMode === mode) {
  12937. return;
  12938. }
  12939. switch (mode) {
  12940. case Engine.ALPHA_DISABLE:
  12941. this._alphaState.alphaBlend = false;
  12942. break;
  12943. case Engine.ALPHA_PREMULTIPLIED:
  12944. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12945. this._alphaState.alphaBlend = true;
  12946. break;
  12947. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12948. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12949. this._alphaState.alphaBlend = true;
  12950. break;
  12951. case Engine.ALPHA_COMBINE:
  12952. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12953. this._alphaState.alphaBlend = true;
  12954. break;
  12955. case Engine.ALPHA_ONEONE:
  12956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12957. this._alphaState.alphaBlend = true;
  12958. break;
  12959. case Engine.ALPHA_ADD:
  12960. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12961. this._alphaState.alphaBlend = true;
  12962. break;
  12963. case Engine.ALPHA_SUBTRACT:
  12964. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12965. this._alphaState.alphaBlend = true;
  12966. break;
  12967. case Engine.ALPHA_MULTIPLY:
  12968. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12969. this._alphaState.alphaBlend = true;
  12970. break;
  12971. case Engine.ALPHA_MAXIMIZED:
  12972. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12973. this._alphaState.alphaBlend = true;
  12974. break;
  12975. case Engine.ALPHA_INTERPOLATE:
  12976. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12977. this._alphaState.alphaBlend = true;
  12978. break;
  12979. case Engine.ALPHA_SCREENMODE:
  12980. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12981. this._alphaState.alphaBlend = true;
  12982. break;
  12983. }
  12984. if (!noDepthWriteChange) {
  12985. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12986. }
  12987. this._alphaMode = mode;
  12988. };
  12989. Engine.prototype.getAlphaMode = function () {
  12990. return this._alphaMode;
  12991. };
  12992. // Textures
  12993. Engine.prototype.wipeCaches = function (bruteForce) {
  12994. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12995. return;
  12996. }
  12997. this._currentEffect = null;
  12998. // 6/8/2017: deltakosh: Should not be required anymore.
  12999. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13000. if (bruteForce) {
  13001. this.resetTextureCache();
  13002. this._currentProgram = null;
  13003. this._stencilState.reset();
  13004. this._depthCullingState.reset();
  13005. this.setDepthFunctionToLessOrEqual();
  13006. this._alphaState.reset();
  13007. }
  13008. this._resetVertexBufferBinding();
  13009. this._cachedIndexBuffer = null;
  13010. this._cachedEffectForVertexBuffers = null;
  13011. this._unbindVertexArrayObject();
  13012. this.bindIndexBuffer(null);
  13013. };
  13014. /**
  13015. * Set the compressed texture format to use, based on the formats you have, and the formats
  13016. * supported by the hardware / browser.
  13017. *
  13018. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13019. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13020. * to API arguments needed to compressed textures. This puts the burden on the container
  13021. * generator to house the arcane code for determining these for current & future formats.
  13022. *
  13023. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13024. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13025. *
  13026. * Note: The result of this call is not taken into account when a texture is base64.
  13027. *
  13028. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13029. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13030. *
  13031. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13032. * @returns The extension selected.
  13033. */
  13034. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13035. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13036. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13037. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13038. return this._textureFormatInUse = this._texturesSupported[i];
  13039. }
  13040. }
  13041. }
  13042. // actively set format to nothing, to allow this to be called more than once
  13043. // and possibly fail the 2nd time
  13044. this._textureFormatInUse = null;
  13045. return null;
  13046. };
  13047. Engine.prototype._createTexture = function () {
  13048. var texture = this._gl.createTexture();
  13049. if (!texture) {
  13050. throw new Error("Unable to create texture");
  13051. }
  13052. return texture;
  13053. };
  13054. /**
  13055. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13056. * @param {string} urlArg- This contains one of the following:
  13057. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13058. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13059. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13060. *
  13061. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13062. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13063. * @param {Scene} scene- Needed for loading to the correct scene.
  13064. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13065. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13066. * @param {callback} onError- Optional callback to be called upon failure.
  13067. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13068. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13069. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13070. *
  13071. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13072. */
  13073. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13074. var _this = this;
  13075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13076. if (onLoad === void 0) { onLoad = null; }
  13077. if (onError === void 0) { onError = null; }
  13078. if (buffer === void 0) { buffer = null; }
  13079. if (fallBack === void 0) { fallBack = null; }
  13080. if (format === void 0) { format = null; }
  13081. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13082. var fromData = url.substr(0, 5) === "data:";
  13083. var fromBlob = url.substr(0, 5) === "blob:";
  13084. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13085. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13086. // establish the file extension, if possible
  13087. var lastDot = url.lastIndexOf('.');
  13088. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13089. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13090. var isTGA = (extension.indexOf(".tga") === 0);
  13091. // determine if a ktx file should be substituted
  13092. var isKTX = false;
  13093. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13094. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13095. isKTX = true;
  13096. }
  13097. if (scene) {
  13098. scene._addPendingData(texture);
  13099. }
  13100. texture.url = url;
  13101. texture.generateMipMaps = !noMipmap;
  13102. texture.samplingMode = samplingMode;
  13103. texture.invertY = invertY;
  13104. if (!this._doNotHandleContextLost) {
  13105. // Keep a link to the buffer only if we plan to handle context lost
  13106. texture._buffer = buffer;
  13107. }
  13108. var onLoadObserver = null;
  13109. if (onLoad && !fallBack) {
  13110. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13111. }
  13112. if (!fallBack)
  13113. this._internalTexturesCache.push(texture);
  13114. var onerror = function (message, exception) {
  13115. if (scene) {
  13116. scene._removePendingData(texture);
  13117. }
  13118. if (onLoadObserver) {
  13119. texture.onLoadedObservable.remove(onLoadObserver);
  13120. }
  13121. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13122. if (isKTX) {
  13123. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13124. }
  13125. else if (BABYLON.Tools.UseFallbackTexture) {
  13126. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13127. }
  13128. if (onError) {
  13129. onError(message || "Unknown error", exception);
  13130. }
  13131. };
  13132. var callback = null;
  13133. // processing for non-image formats
  13134. if (isKTX || isTGA || isDDS) {
  13135. if (isKTX) {
  13136. callback = function (data) {
  13137. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13138. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13139. ktx.uploadLevels(_this._gl, !noMipmap);
  13140. return false;
  13141. }, samplingMode);
  13142. };
  13143. }
  13144. else if (isTGA) {
  13145. callback = function (arrayBuffer) {
  13146. var data = new Uint8Array(arrayBuffer);
  13147. var header = BABYLON.TGATools.GetTGAHeader(data);
  13148. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13149. BABYLON.TGATools.UploadContent(_this._gl, data);
  13150. return false;
  13151. }, samplingMode);
  13152. };
  13153. }
  13154. else if (isDDS) {
  13155. callback = function (data) {
  13156. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13157. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13158. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13159. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13160. return false;
  13161. }, samplingMode);
  13162. };
  13163. }
  13164. if (!buffer) {
  13165. this._loadFile(url, function (data) {
  13166. if (callback) {
  13167. callback(data);
  13168. }
  13169. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13170. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13171. });
  13172. }
  13173. else {
  13174. if (callback) {
  13175. callback(buffer);
  13176. }
  13177. }
  13178. // image format processing
  13179. }
  13180. else {
  13181. var onload = function (img) {
  13182. if (fromBlob && !_this._doNotHandleContextLost) {
  13183. // We need to store the image if we need to rebuild the texture
  13184. // in case of a webgl context lost
  13185. texture._buffer = img;
  13186. }
  13187. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13188. var gl = _this._gl;
  13189. var isPot = (img.width === potWidth && img.height === potHeight);
  13190. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13191. if (isPot) {
  13192. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13193. return false;
  13194. }
  13195. // Using shaders to rescale because canvas.drawImage is lossy
  13196. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13197. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13198. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13203. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13204. _this._releaseTexture(source);
  13205. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13206. continuationCallback();
  13207. });
  13208. return true;
  13209. }, samplingMode);
  13210. };
  13211. if (!fromData || isBase64)
  13212. if (buffer instanceof HTMLImageElement) {
  13213. onload(buffer);
  13214. }
  13215. else {
  13216. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13217. }
  13218. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13219. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13220. else
  13221. onload(buffer);
  13222. }
  13223. return texture;
  13224. };
  13225. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13226. var _this = this;
  13227. var rtt = this.createRenderTargetTexture({
  13228. width: destination.width,
  13229. height: destination.height,
  13230. }, {
  13231. generateMipMaps: false,
  13232. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13233. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13234. generateDepthBuffer: false,
  13235. generateStencilBuffer: false
  13236. });
  13237. if (!this._rescalePostProcess) {
  13238. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13239. }
  13240. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13241. _this._rescalePostProcess.onApply = function (effect) {
  13242. effect._bindTexture("textureSampler", source);
  13243. };
  13244. var hostingScene = scene;
  13245. if (!hostingScene) {
  13246. hostingScene = _this.scenes[_this.scenes.length - 1];
  13247. }
  13248. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13249. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13250. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13251. _this.unBindFramebuffer(rtt);
  13252. _this._releaseTexture(rtt);
  13253. if (onComplete) {
  13254. onComplete();
  13255. }
  13256. });
  13257. };
  13258. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13259. if (compression === void 0) { compression = null; }
  13260. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13261. if (!texture) {
  13262. return;
  13263. }
  13264. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13265. var internalFormat = this._getInternalFormat(format);
  13266. var textureType = this._getWebGLTextureType(type);
  13267. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13268. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13269. if (!this._doNotHandleContextLost) {
  13270. texture._bufferView = data;
  13271. texture.format = format;
  13272. texture.type = type;
  13273. texture.invertY = invertY;
  13274. texture._compression = compression;
  13275. }
  13276. if (texture.width % 4 !== 0) {
  13277. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13278. }
  13279. if (compression && data) {
  13280. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13281. }
  13282. else {
  13283. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13284. }
  13285. if (texture.generateMipMaps) {
  13286. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13287. }
  13288. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13289. // this.resetTextureCache();
  13290. texture.isReady = true;
  13291. };
  13292. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13293. if (compression === void 0) { compression = null; }
  13294. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13295. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13296. texture.baseWidth = width;
  13297. texture.baseHeight = height;
  13298. texture.width = width;
  13299. texture.height = height;
  13300. texture.format = format;
  13301. texture.generateMipMaps = generateMipMaps;
  13302. texture.samplingMode = samplingMode;
  13303. texture.invertY = invertY;
  13304. texture._compression = compression;
  13305. texture.type = type;
  13306. if (!this._doNotHandleContextLost) {
  13307. texture._bufferView = data;
  13308. }
  13309. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13310. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13311. // Filters
  13312. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13313. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13314. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13315. if (generateMipMaps) {
  13316. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13317. }
  13318. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13319. this._internalTexturesCache.push(texture);
  13320. return texture;
  13321. };
  13322. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13323. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13324. texture.baseWidth = width;
  13325. texture.baseHeight = height;
  13326. if (generateMipMaps) {
  13327. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13328. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13329. }
  13330. // this.resetTextureCache();
  13331. texture.width = width;
  13332. texture.height = height;
  13333. texture.isReady = false;
  13334. texture.generateMipMaps = generateMipMaps;
  13335. texture.samplingMode = samplingMode;
  13336. this.updateTextureSamplingMode(samplingMode, texture);
  13337. this._internalTexturesCache.push(texture);
  13338. return texture;
  13339. };
  13340. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13341. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13342. if (texture.isCube) {
  13343. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13344. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13345. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13346. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13347. }
  13348. else if (texture.is3D) {
  13349. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13350. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13351. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13352. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13353. }
  13354. else {
  13355. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13356. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13357. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13358. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13359. }
  13360. texture.samplingMode = samplingMode;
  13361. };
  13362. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13363. if (premulAlpha === void 0) { premulAlpha = false; }
  13364. if (!texture) {
  13365. return;
  13366. }
  13367. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13368. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13369. if (premulAlpha) {
  13370. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13371. }
  13372. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13373. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13374. if (texture.generateMipMaps) {
  13375. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13376. }
  13377. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13378. if (premulAlpha) {
  13379. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13380. }
  13381. texture.isReady = true;
  13382. };
  13383. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13384. if (!texture || texture._isDisabled) {
  13385. return;
  13386. }
  13387. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13388. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13389. try {
  13390. // Testing video texture support
  13391. if (this._videoTextureSupported === undefined) {
  13392. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13393. if (this._gl.getError() !== 0) {
  13394. this._videoTextureSupported = false;
  13395. }
  13396. else {
  13397. this._videoTextureSupported = true;
  13398. }
  13399. }
  13400. // Copy video through the current working canvas if video texture is not supported
  13401. if (!this._videoTextureSupported) {
  13402. if (!texture._workingCanvas) {
  13403. texture._workingCanvas = document.createElement("canvas");
  13404. var context = texture._workingCanvas.getContext("2d");
  13405. if (!context) {
  13406. throw new Error("Unable to get 2d context");
  13407. }
  13408. texture._workingContext = context;
  13409. texture._workingCanvas.width = texture.width;
  13410. texture._workingCanvas.height = texture.height;
  13411. }
  13412. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13413. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13414. }
  13415. else {
  13416. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13417. }
  13418. if (texture.generateMipMaps) {
  13419. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13420. }
  13421. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13422. // this.resetTextureCache();
  13423. texture.isReady = true;
  13424. }
  13425. catch (ex) {
  13426. // Something unexpected
  13427. // Let's disable the texture
  13428. texture._isDisabled = true;
  13429. }
  13430. };
  13431. /**
  13432. * Updates a depth texture Comparison Mode and Function.
  13433. * If the comparison Function is equal to 0, the mode will be set to none.
  13434. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13435. * @param texture The texture to set the comparison function for
  13436. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13437. */
  13438. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13439. if (this.webGLVersion === 1) {
  13440. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13441. return;
  13442. }
  13443. var gl = this._gl;
  13444. if (texture.isCube) {
  13445. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13446. if (comparisonFunction === 0) {
  13447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13449. }
  13450. else {
  13451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13453. }
  13454. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13455. }
  13456. else {
  13457. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13458. if (comparisonFunction === 0) {
  13459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13461. }
  13462. else {
  13463. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13464. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13465. }
  13466. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13467. }
  13468. texture._comparisonFunction = comparisonFunction;
  13469. };
  13470. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13471. var width = size.width || size;
  13472. var height = size.height || size;
  13473. internalTexture.baseWidth = width;
  13474. internalTexture.baseHeight = height;
  13475. internalTexture.width = width;
  13476. internalTexture.height = height;
  13477. internalTexture.isReady = true;
  13478. internalTexture.samples = 1;
  13479. internalTexture.generateMipMaps = false;
  13480. internalTexture._generateDepthBuffer = true;
  13481. internalTexture._generateStencilBuffer = generateStencil;
  13482. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13483. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13484. internalTexture._comparisonFunction = comparisonFunction;
  13485. var gl = this._gl;
  13486. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13487. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13488. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13489. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13490. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13491. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13492. if (comparisonFunction === 0) {
  13493. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13494. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13495. }
  13496. else {
  13497. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13498. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13499. }
  13500. };
  13501. /**
  13502. * Creates a depth stencil texture.
  13503. * This is only available in WebGL 2 or with the depth texture extension available.
  13504. * @param size The size of face edge in the texture.
  13505. * @param options The options defining the texture.
  13506. * @returns The texture
  13507. */
  13508. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13509. if (options.isCube) {
  13510. var width = size.width || size;
  13511. return this._createDepthStencilCubeTexture(width, options);
  13512. }
  13513. else {
  13514. return this._createDepthStencilTexture(size, options);
  13515. }
  13516. };
  13517. /**
  13518. * Creates a depth stencil texture.
  13519. * This is only available in WebGL 2 or with the depth texture extension available.
  13520. * @param size The size of face edge in the texture.
  13521. * @param options The options defining the texture.
  13522. * @returns The texture
  13523. */
  13524. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13525. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13526. if (!this._caps.depthTextureExtension) {
  13527. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13528. return internalTexture;
  13529. }
  13530. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13531. var gl = this._gl;
  13532. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13533. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13534. if (this.webGLVersion > 1) {
  13535. if (internalOptions.generateStencil) {
  13536. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13537. }
  13538. else {
  13539. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13540. }
  13541. }
  13542. else {
  13543. if (internalOptions.generateStencil) {
  13544. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13545. }
  13546. else {
  13547. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13548. }
  13549. }
  13550. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13551. return internalTexture;
  13552. };
  13553. /**
  13554. * Creates a depth stencil cube texture.
  13555. * This is only available in WebGL 2.
  13556. * @param size The size of face edge in the cube texture.
  13557. * @param options The options defining the cube texture.
  13558. * @returns The cube texture
  13559. */
  13560. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13561. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13562. internalTexture.isCube = true;
  13563. if (this.webGLVersion === 1) {
  13564. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13565. return internalTexture;
  13566. }
  13567. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13568. var gl = this._gl;
  13569. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13570. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13571. // Create the depth/stencil buffer
  13572. for (var face = 0; face < 6; face++) {
  13573. if (internalOptions.generateStencil) {
  13574. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13575. }
  13576. else {
  13577. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13578. }
  13579. }
  13580. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13581. return internalTexture;
  13582. };
  13583. /**
  13584. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13585. * @param renderTarget The render target to set the frame buffer for
  13586. */
  13587. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13588. // Create the framebuffer
  13589. var internalTexture = renderTarget.getInternalTexture();
  13590. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13591. return;
  13592. }
  13593. var gl = this._gl;
  13594. var depthStencilTexture = renderTarget.depthStencilTexture;
  13595. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13596. if (depthStencilTexture.isCube) {
  13597. if (depthStencilTexture._generateStencilBuffer) {
  13598. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13599. }
  13600. else {
  13601. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13602. }
  13603. }
  13604. else {
  13605. if (depthStencilTexture._generateStencilBuffer) {
  13606. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13607. }
  13608. else {
  13609. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13610. }
  13611. }
  13612. this.bindUnboundFramebuffer(null);
  13613. };
  13614. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13615. var fullOptions = new RenderTargetCreationOptions();
  13616. if (options !== undefined && typeof options === "object") {
  13617. fullOptions.generateMipMaps = options.generateMipMaps;
  13618. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13619. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13620. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13621. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13622. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13623. }
  13624. else {
  13625. fullOptions.generateMipMaps = options;
  13626. fullOptions.generateDepthBuffer = true;
  13627. fullOptions.generateStencilBuffer = false;
  13628. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13629. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13630. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13631. }
  13632. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13633. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13634. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13635. }
  13636. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13637. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13638. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13639. }
  13640. var gl = this._gl;
  13641. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13642. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13643. var width = size.width || size;
  13644. var height = size.height || size;
  13645. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13646. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13647. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13648. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13649. }
  13650. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13651. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13652. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13653. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13654. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13655. // Create the framebuffer
  13656. var framebuffer = gl.createFramebuffer();
  13657. this.bindUnboundFramebuffer(framebuffer);
  13658. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13659. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13660. if (fullOptions.generateMipMaps) {
  13661. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13662. }
  13663. // Unbind
  13664. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13665. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13666. this.bindUnboundFramebuffer(null);
  13667. texture._framebuffer = framebuffer;
  13668. texture.baseWidth = width;
  13669. texture.baseHeight = height;
  13670. texture.width = width;
  13671. texture.height = height;
  13672. texture.isReady = true;
  13673. texture.samples = 1;
  13674. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13675. texture.samplingMode = fullOptions.samplingMode;
  13676. texture.type = fullOptions.type;
  13677. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13678. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13679. // this.resetTextureCache();
  13680. this._internalTexturesCache.push(texture);
  13681. return texture;
  13682. };
  13683. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13684. var generateMipMaps = false;
  13685. var generateDepthBuffer = true;
  13686. var generateStencilBuffer = false;
  13687. var generateDepthTexture = false;
  13688. var textureCount = 1;
  13689. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13690. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13691. var types = [], samplingModes = [];
  13692. if (options !== undefined) {
  13693. generateMipMaps = options.generateMipMaps;
  13694. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13695. generateStencilBuffer = options.generateStencilBuffer;
  13696. generateDepthTexture = options.generateDepthTexture;
  13697. textureCount = options.textureCount || 1;
  13698. if (options.types) {
  13699. types = options.types;
  13700. }
  13701. if (options.samplingModes) {
  13702. samplingModes = options.samplingModes;
  13703. }
  13704. }
  13705. var gl = this._gl;
  13706. // Create the framebuffer
  13707. var framebuffer = gl.createFramebuffer();
  13708. this.bindUnboundFramebuffer(framebuffer);
  13709. var width = size.width || size;
  13710. var height = size.height || size;
  13711. var textures = [];
  13712. var attachments = [];
  13713. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13714. for (var i = 0; i < textureCount; i++) {
  13715. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13716. var type = types[i] || defaultType;
  13717. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13718. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13719. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13720. }
  13721. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13722. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13723. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13724. }
  13725. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13726. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13727. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13728. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13729. }
  13730. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13731. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13732. textures.push(texture);
  13733. attachments.push(attachment);
  13734. gl.activeTexture(gl["TEXTURE" + i]);
  13735. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13736. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13737. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13738. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13739. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13740. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13741. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13742. if (generateMipMaps) {
  13743. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13744. }
  13745. // Unbind
  13746. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13747. texture._framebuffer = framebuffer;
  13748. texture._depthStencilBuffer = depthStencilBuffer;
  13749. texture.baseWidth = width;
  13750. texture.baseHeight = height;
  13751. texture.width = width;
  13752. texture.height = height;
  13753. texture.isReady = true;
  13754. texture.samples = 1;
  13755. texture.generateMipMaps = generateMipMaps;
  13756. texture.samplingMode = samplingMode;
  13757. texture.type = type;
  13758. texture._generateDepthBuffer = generateDepthBuffer;
  13759. texture._generateStencilBuffer = generateStencilBuffer;
  13760. texture._attachments = attachments;
  13761. this._internalTexturesCache.push(texture);
  13762. }
  13763. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13764. // Depth texture
  13765. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13766. gl.activeTexture(gl.TEXTURE0);
  13767. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13768. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13769. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13770. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13771. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13772. 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);
  13773. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13774. depthTexture._framebuffer = framebuffer;
  13775. depthTexture.baseWidth = width;
  13776. depthTexture.baseHeight = height;
  13777. depthTexture.width = width;
  13778. depthTexture.height = height;
  13779. depthTexture.isReady = true;
  13780. depthTexture.samples = 1;
  13781. depthTexture.generateMipMaps = generateMipMaps;
  13782. depthTexture.samplingMode = gl.NEAREST;
  13783. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13784. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13785. textures.push(depthTexture);
  13786. this._internalTexturesCache.push(depthTexture);
  13787. }
  13788. gl.drawBuffers(attachments);
  13789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13790. this.bindUnboundFramebuffer(null);
  13791. this.resetTextureCache();
  13792. return textures;
  13793. };
  13794. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13795. if (samples === void 0) { samples = 1; }
  13796. var depthStencilBuffer = null;
  13797. var gl = this._gl;
  13798. // Create the depth/stencil buffer
  13799. if (generateStencilBuffer) {
  13800. depthStencilBuffer = gl.createRenderbuffer();
  13801. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13802. if (samples > 1) {
  13803. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13804. }
  13805. else {
  13806. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13807. }
  13808. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13809. }
  13810. else if (generateDepthBuffer) {
  13811. depthStencilBuffer = gl.createRenderbuffer();
  13812. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13813. if (samples > 1) {
  13814. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13815. }
  13816. else {
  13817. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13818. }
  13819. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13820. }
  13821. return depthStencilBuffer;
  13822. };
  13823. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13824. if (this.webGLVersion < 2 || !texture) {
  13825. return 1;
  13826. }
  13827. if (texture.samples === samples) {
  13828. return samples;
  13829. }
  13830. var gl = this._gl;
  13831. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13832. // Dispose previous render buffers
  13833. if (texture._depthStencilBuffer) {
  13834. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13835. texture._depthStencilBuffer = null;
  13836. }
  13837. if (texture._MSAAFramebuffer) {
  13838. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13839. texture._MSAAFramebuffer = null;
  13840. }
  13841. if (texture._MSAARenderBuffer) {
  13842. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13843. texture._MSAARenderBuffer = null;
  13844. }
  13845. if (samples > 1) {
  13846. var framebuffer = gl.createFramebuffer();
  13847. if (!framebuffer) {
  13848. throw new Error("Unable to create multi sampled framebuffer");
  13849. }
  13850. texture._MSAAFramebuffer = framebuffer;
  13851. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13852. var colorRenderbuffer = gl.createRenderbuffer();
  13853. if (!colorRenderbuffer) {
  13854. throw new Error("Unable to create multi sampled framebuffer");
  13855. }
  13856. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13857. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13858. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13859. texture._MSAARenderBuffer = colorRenderbuffer;
  13860. }
  13861. else {
  13862. this.bindUnboundFramebuffer(texture._framebuffer);
  13863. }
  13864. texture.samples = samples;
  13865. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13866. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13867. this.bindUnboundFramebuffer(null);
  13868. return samples;
  13869. };
  13870. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13871. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13872. return 1;
  13873. }
  13874. if (textures[0].samples === samples) {
  13875. return samples;
  13876. }
  13877. var gl = this._gl;
  13878. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13879. // Dispose previous render buffers
  13880. if (textures[0]._depthStencilBuffer) {
  13881. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13882. textures[0]._depthStencilBuffer = null;
  13883. }
  13884. if (textures[0]._MSAAFramebuffer) {
  13885. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13886. textures[0]._MSAAFramebuffer = null;
  13887. }
  13888. for (var i = 0; i < textures.length; i++) {
  13889. if (textures[i]._MSAARenderBuffer) {
  13890. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13891. textures[i]._MSAARenderBuffer = null;
  13892. }
  13893. }
  13894. if (samples > 1) {
  13895. var framebuffer = gl.createFramebuffer();
  13896. if (!framebuffer) {
  13897. throw new Error("Unable to create multi sampled framebuffer");
  13898. }
  13899. this.bindUnboundFramebuffer(framebuffer);
  13900. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13901. var attachments = [];
  13902. for (var i = 0; i < textures.length; i++) {
  13903. var texture = textures[i];
  13904. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13905. var colorRenderbuffer = gl.createRenderbuffer();
  13906. if (!colorRenderbuffer) {
  13907. throw new Error("Unable to create multi sampled framebuffer");
  13908. }
  13909. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13910. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13911. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13912. texture._MSAAFramebuffer = framebuffer;
  13913. texture._MSAARenderBuffer = colorRenderbuffer;
  13914. texture.samples = samples;
  13915. texture._depthStencilBuffer = depthStencilBuffer;
  13916. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13917. attachments.push(attachment);
  13918. }
  13919. gl.drawBuffers(attachments);
  13920. }
  13921. else {
  13922. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13923. }
  13924. this.bindUnboundFramebuffer(null);
  13925. return samples;
  13926. };
  13927. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13928. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13929. };
  13930. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13931. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13932. };
  13933. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13934. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13935. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13936. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13937. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13938. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13939. }
  13940. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13941. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13942. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13943. }
  13944. var gl = this._gl;
  13945. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13946. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13947. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13948. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13949. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13950. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13951. }
  13952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13956. for (var face = 0; face < 6; face++) {
  13957. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13958. }
  13959. // Create the framebuffer
  13960. var framebuffer = gl.createFramebuffer();
  13961. this.bindUnboundFramebuffer(framebuffer);
  13962. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13963. // MipMaps
  13964. if (fullOptions.generateMipMaps) {
  13965. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13966. }
  13967. // Unbind
  13968. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13969. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13970. this.bindUnboundFramebuffer(null);
  13971. texture._framebuffer = framebuffer;
  13972. texture.width = size;
  13973. texture.height = size;
  13974. texture.isReady = true;
  13975. texture.isCube = true;
  13976. texture.samples = 1;
  13977. texture.generateMipMaps = fullOptions.generateMipMaps;
  13978. texture.samplingMode = fullOptions.samplingMode;
  13979. texture.type = fullOptions.type;
  13980. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13981. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13982. this._internalTexturesCache.push(texture);
  13983. return texture;
  13984. };
  13985. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13986. var _this = this;
  13987. if (onLoad === void 0) { onLoad = null; }
  13988. if (onError === void 0) { onError = null; }
  13989. if (forcedExtension === void 0) { forcedExtension = null; }
  13990. var callback = function (loadData) {
  13991. if (!loadData) {
  13992. if (onLoad) {
  13993. onLoad(null);
  13994. }
  13995. return;
  13996. }
  13997. var texture = loadData.texture;
  13998. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13999. texture._lodGenerationScale = scale;
  14000. texture._lodGenerationOffset = offset;
  14001. if (_this._caps.textureLOD) {
  14002. // Do not add extra process if texture lod is supported.
  14003. if (onLoad) {
  14004. onLoad(texture);
  14005. }
  14006. return;
  14007. }
  14008. var mipSlices = 3;
  14009. var gl = _this._gl;
  14010. var width = loadData.width;
  14011. if (!width) {
  14012. return;
  14013. }
  14014. var textures = [];
  14015. for (var i = 0; i < mipSlices; i++) {
  14016. //compute LOD from even spacing in smoothness (matching shader calculation)
  14017. var smoothness = i / (mipSlices - 1);
  14018. var roughness = 1 - smoothness;
  14019. var minLODIndex = offset; // roughness = 0
  14020. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14021. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14022. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14023. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14024. glTextureFromLod.isCube = true;
  14025. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14026. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14027. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14028. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14029. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14030. if (loadData.isDDS) {
  14031. var info = loadData.info;
  14032. var data = loadData.data;
  14033. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14034. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14035. }
  14036. else {
  14037. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14038. }
  14039. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14040. // Wrap in a base texture for easy binding.
  14041. var lodTexture = new BABYLON.BaseTexture(scene);
  14042. lodTexture.isCube = true;
  14043. lodTexture._texture = glTextureFromLod;
  14044. glTextureFromLod.isReady = true;
  14045. textures.push(lodTexture);
  14046. }
  14047. texture._lodTextureHigh = textures[2];
  14048. texture._lodTextureMid = textures[1];
  14049. texture._lodTextureLow = textures[0];
  14050. if (onLoad) {
  14051. onLoad(texture);
  14052. }
  14053. };
  14054. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14055. };
  14056. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14057. var _this = this;
  14058. if (onLoad === void 0) { onLoad = null; }
  14059. if (onError === void 0) { onError = null; }
  14060. if (forcedExtension === void 0) { forcedExtension = null; }
  14061. var gl = this._gl;
  14062. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14063. texture.isCube = true;
  14064. texture.url = rootUrl;
  14065. texture.generateMipMaps = !noMipmap;
  14066. if (!this._doNotHandleContextLost) {
  14067. texture._extension = forcedExtension;
  14068. texture._files = files;
  14069. }
  14070. var isKTX = false;
  14071. var isDDS = false;
  14072. var lastDot = rootUrl.lastIndexOf('.');
  14073. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14074. if (this._textureFormatInUse) {
  14075. extension = this._textureFormatInUse;
  14076. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14077. isKTX = true;
  14078. }
  14079. else {
  14080. isDDS = (extension === ".dds");
  14081. }
  14082. var onerror = function (request, exception) {
  14083. if (onError && request) {
  14084. onError(request.status + " " + request.statusText, exception);
  14085. }
  14086. };
  14087. if (isKTX) {
  14088. this._loadFile(rootUrl, function (data) {
  14089. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14090. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14091. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14092. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14093. ktx.uploadLevels(_this._gl, !noMipmap);
  14094. _this.setCubeMapTextureParams(gl, loadMipmap);
  14095. texture.width = ktx.pixelWidth;
  14096. texture.height = ktx.pixelHeight;
  14097. texture.isReady = true;
  14098. }, undefined, undefined, true, onerror);
  14099. }
  14100. else if (isDDS) {
  14101. if (files && files.length === 6) {
  14102. this._cascadeLoadFiles(scene, function (imgs) {
  14103. var info;
  14104. var loadMipmap = false;
  14105. var width = 0;
  14106. for (var index = 0; index < imgs.length; index++) {
  14107. var data = imgs[index];
  14108. info = BABYLON.DDSTools.GetDDSInfo(data);
  14109. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14110. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14111. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14112. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14113. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14114. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14115. }
  14116. texture.width = info.width;
  14117. texture.height = info.height;
  14118. texture.type = info.textureType;
  14119. width = info.width;
  14120. }
  14121. _this.setCubeMapTextureParams(gl, loadMipmap);
  14122. texture.isReady = true;
  14123. if (onLoad) {
  14124. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14125. }
  14126. }, files, onError);
  14127. }
  14128. else {
  14129. this._loadFile(rootUrl, function (data) {
  14130. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14131. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14132. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14133. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14134. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14135. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14136. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14137. }
  14138. _this.setCubeMapTextureParams(gl, loadMipmap);
  14139. texture.width = info.width;
  14140. texture.height = info.height;
  14141. texture.isReady = true;
  14142. texture.type = info.textureType;
  14143. if (onLoad) {
  14144. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14145. }
  14146. }, undefined, undefined, true, onerror);
  14147. }
  14148. }
  14149. else {
  14150. if (!files) {
  14151. throw new Error("Cannot load cubemap because files were not defined");
  14152. }
  14153. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14154. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14155. var height = width;
  14156. _this._prepareWorkingCanvas();
  14157. if (!_this._workingCanvas || !_this._workingContext) {
  14158. return;
  14159. }
  14160. _this._workingCanvas.width = width;
  14161. _this._workingCanvas.height = height;
  14162. var faces = [
  14163. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14164. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14165. ];
  14166. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14167. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14168. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14169. for (var index = 0; index < faces.length; index++) {
  14170. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14171. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14172. }
  14173. if (!noMipmap) {
  14174. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14175. }
  14176. _this.setCubeMapTextureParams(gl, !noMipmap);
  14177. texture.width = width;
  14178. texture.height = height;
  14179. texture.isReady = true;
  14180. if (format) {
  14181. texture.format = format;
  14182. }
  14183. texture.onLoadedObservable.notifyObservers(texture);
  14184. texture.onLoadedObservable.clear();
  14185. if (onLoad) {
  14186. onLoad();
  14187. }
  14188. }, files, onError);
  14189. }
  14190. this._internalTexturesCache.push(texture);
  14191. return texture;
  14192. };
  14193. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14194. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14195. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14196. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14198. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14199. // this.resetTextureCache();
  14200. };
  14201. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14202. if (compression === void 0) { compression = null; }
  14203. if (level === void 0) { level = 0; }
  14204. texture._bufferViewArray = data;
  14205. texture.format = format;
  14206. texture.type = type;
  14207. texture.invertY = invertY;
  14208. texture._compression = compression;
  14209. var gl = this._gl;
  14210. var textureType = this._getWebGLTextureType(type);
  14211. var internalFormat = this._getInternalFormat(format);
  14212. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14213. var needConversion = false;
  14214. if (internalFormat === gl.RGB) {
  14215. internalFormat = gl.RGBA;
  14216. needConversion = true;
  14217. }
  14218. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14219. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14220. if (texture.width % 4 !== 0) {
  14221. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14222. }
  14223. // Data are known to be in +X +Y +Z -X -Y -Z
  14224. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14225. var faceData = data[faceIndex];
  14226. if (compression) {
  14227. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14228. }
  14229. else {
  14230. if (needConversion) {
  14231. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14232. }
  14233. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14234. }
  14235. }
  14236. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14237. if (isPot && texture.generateMipMaps && level === 0) {
  14238. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14239. }
  14240. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14241. // this.resetTextureCache();
  14242. texture.isReady = true;
  14243. };
  14244. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14245. if (compression === void 0) { compression = null; }
  14246. var gl = this._gl;
  14247. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14248. texture.isCube = true;
  14249. texture.generateMipMaps = generateMipMaps;
  14250. texture.format = format;
  14251. texture.type = type;
  14252. if (!this._doNotHandleContextLost) {
  14253. texture._bufferViewArray = data;
  14254. }
  14255. var textureType = this._getWebGLTextureType(type);
  14256. var internalFormat = this._getInternalFormat(format);
  14257. if (internalFormat === gl.RGB) {
  14258. internalFormat = gl.RGBA;
  14259. }
  14260. var width = size;
  14261. var height = width;
  14262. texture.width = width;
  14263. texture.height = height;
  14264. // Double check on POT to generate Mips.
  14265. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14266. if (!isPot) {
  14267. generateMipMaps = false;
  14268. }
  14269. // Upload data if needed. The texture won't be ready until then.
  14270. if (data) {
  14271. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14272. }
  14273. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14274. // Filters
  14275. if (data && generateMipMaps) {
  14276. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14277. }
  14278. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14281. }
  14282. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14285. }
  14286. else {
  14287. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14289. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14290. }
  14291. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14293. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14294. return texture;
  14295. };
  14296. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14297. var _this = this;
  14298. if (onLoad === void 0) { onLoad = null; }
  14299. if (onError === void 0) { onError = null; }
  14300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14301. if (invertY === void 0) { invertY = false; }
  14302. var gl = this._gl;
  14303. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14304. scene._addPendingData(texture);
  14305. texture.url = url;
  14306. this._internalTexturesCache.push(texture);
  14307. var onerror = function (request, exception) {
  14308. scene._removePendingData(texture);
  14309. if (onError && request) {
  14310. onError(request.status + " " + request.statusText, exception);
  14311. }
  14312. };
  14313. var internalCallback = function (data) {
  14314. var width = texture.width;
  14315. var faceDataArrays = callback(data);
  14316. if (!faceDataArrays) {
  14317. return;
  14318. }
  14319. if (mipmmapGenerator) {
  14320. var textureType = _this._getWebGLTextureType(type);
  14321. var internalFormat = _this._getInternalFormat(format);
  14322. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14323. var needConversion = false;
  14324. if (internalFormat === gl.RGB) {
  14325. internalFormat = gl.RGBA;
  14326. needConversion = true;
  14327. }
  14328. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14329. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14330. var mipData = mipmmapGenerator(faceDataArrays);
  14331. for (var level = 0; level < mipData.length; level++) {
  14332. var mipSize = width >> level;
  14333. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14334. var mipFaceData = mipData[level][faceIndex];
  14335. if (needConversion) {
  14336. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14337. }
  14338. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14339. }
  14340. }
  14341. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14342. }
  14343. else {
  14344. texture.generateMipMaps = !noMipmap;
  14345. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14346. }
  14347. texture.isReady = true;
  14348. // this.resetTextureCache();
  14349. scene._removePendingData(texture);
  14350. if (onLoad) {
  14351. onLoad();
  14352. }
  14353. };
  14354. this._loadFile(url, function (data) {
  14355. internalCallback(data);
  14356. }, undefined, scene.database, true, onerror);
  14357. return texture;
  14358. };
  14359. ;
  14360. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14361. if (compression === void 0) { compression = null; }
  14362. var internalFormat = this._getInternalFormat(format);
  14363. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14364. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14365. if (!this._doNotHandleContextLost) {
  14366. texture._bufferView = data;
  14367. texture.format = format;
  14368. texture.invertY = invertY;
  14369. texture._compression = compression;
  14370. }
  14371. if (texture.width % 4 !== 0) {
  14372. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14373. }
  14374. if (compression && data) {
  14375. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14376. }
  14377. else {
  14378. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14379. }
  14380. if (texture.generateMipMaps) {
  14381. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14382. }
  14383. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14384. // this.resetTextureCache();
  14385. texture.isReady = true;
  14386. };
  14387. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14388. if (compression === void 0) { compression = null; }
  14389. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14390. texture.baseWidth = width;
  14391. texture.baseHeight = height;
  14392. texture.baseDepth = depth;
  14393. texture.width = width;
  14394. texture.height = height;
  14395. texture.depth = depth;
  14396. texture.format = format;
  14397. texture.generateMipMaps = generateMipMaps;
  14398. texture.samplingMode = samplingMode;
  14399. texture.is3D = true;
  14400. if (!this._doNotHandleContextLost) {
  14401. texture._bufferView = data;
  14402. }
  14403. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14404. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14405. // Filters
  14406. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14407. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14408. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14409. if (generateMipMaps) {
  14410. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14411. }
  14412. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14413. this._internalTexturesCache.push(texture);
  14414. return texture;
  14415. };
  14416. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14417. var gl = this._gl;
  14418. if (!gl) {
  14419. return;
  14420. }
  14421. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14424. if (!noMipmap && !isCompressed) {
  14425. gl.generateMipmap(gl.TEXTURE_2D);
  14426. }
  14427. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14428. // this.resetTextureCache();
  14429. if (scene) {
  14430. scene._removePendingData(texture);
  14431. }
  14432. texture.onLoadedObservable.notifyObservers(texture);
  14433. texture.onLoadedObservable.clear();
  14434. };
  14435. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14436. var _this = this;
  14437. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14438. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14439. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14440. var gl = this._gl;
  14441. if (!gl) {
  14442. return;
  14443. }
  14444. if (!texture._webGLTexture) {
  14445. // this.resetTextureCache();
  14446. if (scene) {
  14447. scene._removePendingData(texture);
  14448. }
  14449. return;
  14450. }
  14451. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14452. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14453. texture.baseWidth = width;
  14454. texture.baseHeight = height;
  14455. texture.width = potWidth;
  14456. texture.height = potHeight;
  14457. texture.isReady = true;
  14458. if (processFunction(potWidth, potHeight, function () {
  14459. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14460. })) {
  14461. // Returning as texture needs extra async steps
  14462. return;
  14463. }
  14464. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14465. };
  14466. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14467. // Create new RGBA data container.
  14468. var rgbaData;
  14469. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14470. rgbaData = new Float32Array(width * height * 4);
  14471. }
  14472. else {
  14473. rgbaData = new Uint32Array(width * height * 4);
  14474. }
  14475. // Convert each pixel.
  14476. for (var x = 0; x < width; x++) {
  14477. for (var y = 0; y < height; y++) {
  14478. var index = (y * width + x) * 3;
  14479. var newIndex = (y * width + x) * 4;
  14480. // Map Old Value to new value.
  14481. rgbaData[newIndex + 0] = rgbData[index + 0];
  14482. rgbaData[newIndex + 1] = rgbData[index + 1];
  14483. rgbaData[newIndex + 2] = rgbData[index + 2];
  14484. // Add fully opaque alpha channel.
  14485. rgbaData[newIndex + 3] = 1;
  14486. }
  14487. }
  14488. return rgbaData;
  14489. };
  14490. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14491. var gl = this._gl;
  14492. if (texture._framebuffer) {
  14493. gl.deleteFramebuffer(texture._framebuffer);
  14494. texture._framebuffer = null;
  14495. }
  14496. if (texture._depthStencilBuffer) {
  14497. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14498. texture._depthStencilBuffer = null;
  14499. }
  14500. if (texture._MSAAFramebuffer) {
  14501. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14502. texture._MSAAFramebuffer = null;
  14503. }
  14504. if (texture._MSAARenderBuffer) {
  14505. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14506. texture._MSAARenderBuffer = null;
  14507. }
  14508. };
  14509. Engine.prototype._releaseTexture = function (texture) {
  14510. var gl = this._gl;
  14511. this._releaseFramebufferObjects(texture);
  14512. gl.deleteTexture(texture._webGLTexture);
  14513. // Unbind channels
  14514. this.unbindAllTextures();
  14515. var index = this._internalTexturesCache.indexOf(texture);
  14516. if (index !== -1) {
  14517. this._internalTexturesCache.splice(index, 1);
  14518. }
  14519. // Integrated fixed lod samplers.
  14520. if (texture._lodTextureHigh) {
  14521. texture._lodTextureHigh.dispose();
  14522. }
  14523. if (texture._lodTextureMid) {
  14524. texture._lodTextureMid.dispose();
  14525. }
  14526. if (texture._lodTextureLow) {
  14527. texture._lodTextureLow.dispose();
  14528. }
  14529. // Set output texture of post process to null if the texture has been released/disposed
  14530. this.scenes.forEach(function (scene) {
  14531. scene.postProcesses.forEach(function (postProcess) {
  14532. if (postProcess._outputTexture == texture) {
  14533. postProcess._outputTexture = null;
  14534. }
  14535. });
  14536. scene.cameras.forEach(function (camera) {
  14537. camera._postProcesses.forEach(function (postProcess) {
  14538. if (postProcess) {
  14539. if (postProcess._outputTexture == texture) {
  14540. postProcess._outputTexture = null;
  14541. }
  14542. }
  14543. });
  14544. });
  14545. });
  14546. };
  14547. Engine.prototype.setProgram = function (program) {
  14548. if (this._currentProgram !== program) {
  14549. this._gl.useProgram(program);
  14550. this._currentProgram = program;
  14551. }
  14552. };
  14553. Engine.prototype.bindSamplers = function (effect) {
  14554. this.setProgram(effect.getProgram());
  14555. var samplers = effect.getSamplers();
  14556. for (var index = 0; index < samplers.length; index++) {
  14557. var uniform = effect.getUniform(samplers[index]);
  14558. if (uniform) {
  14559. this._boundUniforms[index] = uniform;
  14560. }
  14561. }
  14562. this._currentEffect = null;
  14563. };
  14564. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14565. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14566. return;
  14567. }
  14568. // Remove
  14569. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14570. // Bind last to it
  14571. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14572. // Bind to dummy
  14573. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14574. };
  14575. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14576. if (!internalTexture) {
  14577. return -1;
  14578. }
  14579. internalTexture._initialSlot = channel;
  14580. if (this.disableTextureBindingOptimization) {
  14581. if (channel !== internalTexture._designatedSlot) {
  14582. this._textureCollisions.addCount(1, false);
  14583. }
  14584. }
  14585. else {
  14586. if (channel !== internalTexture._designatedSlot) {
  14587. if (internalTexture._designatedSlot > -1) {
  14588. return internalTexture._designatedSlot;
  14589. }
  14590. else {
  14591. // No slot for this texture, let's pick a new one (if we find a free slot)
  14592. if (this._nextFreeTextureSlots.length) {
  14593. return this._nextFreeTextureSlots[0];
  14594. }
  14595. // We need to recycle the oldest bound texture, sorry.
  14596. this._textureCollisions.addCount(1, false);
  14597. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14598. }
  14599. }
  14600. }
  14601. return channel;
  14602. };
  14603. Engine.prototype._linkTrackers = function (previous, next) {
  14604. previous.next = next;
  14605. next.previous = previous;
  14606. };
  14607. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14608. var currentSlot = internalTexture._designatedSlot;
  14609. if (currentSlot === -1) {
  14610. return -1;
  14611. }
  14612. internalTexture._designatedSlot = -1;
  14613. if (this.disableTextureBindingOptimization) {
  14614. return -1;
  14615. }
  14616. // Remove from bound list
  14617. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14618. // Free the slot
  14619. this._boundTexturesCache[currentSlot] = null;
  14620. this._nextFreeTextureSlots.push(currentSlot);
  14621. return currentSlot;
  14622. };
  14623. Engine.prototype._activateCurrentTexture = function () {
  14624. if (this._currentTextureChannel !== this._activeChannel) {
  14625. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14626. this._currentTextureChannel = this._activeChannel;
  14627. }
  14628. };
  14629. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14630. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14631. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14632. this._activeChannel = texture._designatedSlot;
  14633. }
  14634. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14635. var isTextureForRendering = texture && texture._initialSlot > -1;
  14636. if (currentTextureBound !== texture) {
  14637. if (currentTextureBound) {
  14638. this._removeDesignatedSlot(currentTextureBound);
  14639. }
  14640. this._activateCurrentTexture();
  14641. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14642. this._boundTexturesCache[this._activeChannel] = texture;
  14643. if (texture) {
  14644. if (!this.disableTextureBindingOptimization) {
  14645. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14646. if (slotIndex > -1) {
  14647. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14648. }
  14649. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14650. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14651. }
  14652. texture._designatedSlot = this._activeChannel;
  14653. }
  14654. }
  14655. else if (forTextureDataUpdate) {
  14656. this._activateCurrentTexture();
  14657. }
  14658. if (isTextureForRendering && !forTextureDataUpdate) {
  14659. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14660. }
  14661. };
  14662. Engine.prototype._bindTexture = function (channel, texture) {
  14663. if (channel < 0) {
  14664. return;
  14665. }
  14666. if (texture) {
  14667. channel = this._getCorrectTextureChannel(channel, texture);
  14668. }
  14669. this._activeChannel = channel;
  14670. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14671. };
  14672. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14673. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14674. };
  14675. /**
  14676. * Binds the output of the passed in post process to the texture channel specified
  14677. * @param channel The channel the texture should be bound to
  14678. * @param postProcess The post process which's output should be bound
  14679. */
  14680. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14681. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14682. };
  14683. Engine.prototype.unbindAllTextures = function () {
  14684. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14685. this._activeChannel = channel;
  14686. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14687. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14688. if (this.webGLVersion > 1) {
  14689. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14690. }
  14691. }
  14692. };
  14693. /**
  14694. * Sets a texture to the according uniform.
  14695. * @param channel The texture channel
  14696. * @param uniform The uniform to set
  14697. * @param texture The texture to apply
  14698. */
  14699. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14700. if (channel < 0) {
  14701. return;
  14702. }
  14703. if (uniform) {
  14704. this._boundUniforms[channel] = uniform;
  14705. }
  14706. this._setTexture(channel, texture);
  14707. };
  14708. /**
  14709. * Sets a depth stencil texture from a render target to the according uniform.
  14710. * @param channel The texture channel
  14711. * @param uniform The uniform to set
  14712. * @param texture The render target texture containing the depth stencil texture to apply
  14713. */
  14714. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14715. if (channel < 0) {
  14716. return;
  14717. }
  14718. if (uniform) {
  14719. this._boundUniforms[channel] = uniform;
  14720. }
  14721. if (!texture || !texture.depthStencilTexture) {
  14722. this._setTexture(channel, null);
  14723. }
  14724. else {
  14725. this._setTexture(channel, texture, false, true);
  14726. }
  14727. };
  14728. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14729. var uniform = this._boundUniforms[sourceSlot];
  14730. if (uniform._currentState === destination) {
  14731. return;
  14732. }
  14733. this._gl.uniform1i(uniform, destination);
  14734. uniform._currentState = destination;
  14735. };
  14736. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14737. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14738. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14739. // Not ready?
  14740. if (!texture) {
  14741. if (this._boundTexturesCache[channel] != null) {
  14742. this._activeChannel = channel;
  14743. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14744. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14745. if (this.webGLVersion > 1) {
  14746. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14747. }
  14748. }
  14749. return false;
  14750. }
  14751. // Video
  14752. if (texture.video) {
  14753. this._activeChannel = channel;
  14754. texture.update();
  14755. }
  14756. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14757. texture.delayLoad();
  14758. return false;
  14759. }
  14760. var internalTexture;
  14761. if (depthStencilTexture) {
  14762. internalTexture = texture.depthStencilTexture;
  14763. }
  14764. else if (texture.isReady()) {
  14765. internalTexture = texture.getInternalTexture();
  14766. }
  14767. else if (texture.isCube) {
  14768. internalTexture = this.emptyCubeTexture;
  14769. }
  14770. else if (texture.is3D) {
  14771. internalTexture = this.emptyTexture3D;
  14772. }
  14773. else {
  14774. internalTexture = this.emptyTexture;
  14775. }
  14776. if (!isPartOfTextureArray) {
  14777. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14778. }
  14779. if (this._boundTexturesCache[channel] === internalTexture) {
  14780. this._moveBoundTextureOnTop(internalTexture);
  14781. if (!isPartOfTextureArray) {
  14782. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14783. }
  14784. return false;
  14785. }
  14786. this._activeChannel = channel;
  14787. if (internalTexture && internalTexture.is3D) {
  14788. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14789. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14790. internalTexture._cachedWrapU = texture.wrapU;
  14791. switch (texture.wrapU) {
  14792. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14793. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14794. break;
  14795. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14796. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14797. break;
  14798. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14799. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14800. break;
  14801. }
  14802. }
  14803. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14804. internalTexture._cachedWrapV = texture.wrapV;
  14805. switch (texture.wrapV) {
  14806. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14807. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14808. break;
  14809. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14810. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14811. break;
  14812. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14813. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14814. break;
  14815. }
  14816. }
  14817. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14818. internalTexture._cachedWrapR = texture.wrapR;
  14819. switch (texture.wrapR) {
  14820. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14821. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14822. break;
  14823. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14824. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14825. break;
  14826. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14827. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14828. break;
  14829. }
  14830. }
  14831. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14832. }
  14833. else if (internalTexture && internalTexture.isCube) {
  14834. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14835. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14836. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14837. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14838. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14839. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14840. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14841. }
  14842. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14843. }
  14844. else {
  14845. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14846. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14847. internalTexture._cachedWrapU = texture.wrapU;
  14848. switch (texture.wrapU) {
  14849. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14850. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14851. break;
  14852. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14853. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14854. break;
  14855. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14856. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14857. break;
  14858. }
  14859. }
  14860. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14861. internalTexture._cachedWrapV = texture.wrapV;
  14862. switch (texture.wrapV) {
  14863. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14864. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14865. break;
  14866. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14867. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14868. break;
  14869. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14871. break;
  14872. }
  14873. }
  14874. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14875. }
  14876. return true;
  14877. };
  14878. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14879. if (channel < 0 || !uniform) {
  14880. return;
  14881. }
  14882. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14883. this._textureUnits = new Int32Array(textures.length);
  14884. }
  14885. for (var i = 0; i < textures.length; i++) {
  14886. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14887. }
  14888. this._gl.uniform1iv(uniform, this._textureUnits);
  14889. for (var index = 0; index < textures.length; index++) {
  14890. this._setTexture(this._textureUnits[index], textures[index], true);
  14891. }
  14892. };
  14893. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14894. var internalTexture = texture.getInternalTexture();
  14895. if (!internalTexture) {
  14896. return;
  14897. }
  14898. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14899. var value = texture.anisotropicFilteringLevel;
  14900. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14901. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14902. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14903. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14904. }
  14905. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14906. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14907. internalTexture._cachedAnisotropicFilteringLevel = value;
  14908. }
  14909. };
  14910. Engine.prototype.readPixels = function (x, y, width, height) {
  14911. var data = new Uint8Array(height * width * 4);
  14912. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14913. return data;
  14914. };
  14915. /**
  14916. * Add an externaly attached data from its key.
  14917. * This method call will fail and return false, if such key already exists.
  14918. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14919. * @param key the unique key that identifies the data
  14920. * @param data the data object to associate to the key for this Engine instance
  14921. * @return true if no such key were already present and the data was added successfully, false otherwise
  14922. */
  14923. Engine.prototype.addExternalData = function (key, data) {
  14924. if (!this._externalData) {
  14925. this._externalData = new BABYLON.StringDictionary();
  14926. }
  14927. return this._externalData.add(key, data);
  14928. };
  14929. /**
  14930. * Get an externaly attached data from its key
  14931. * @param key the unique key that identifies the data
  14932. * @return the associated data, if present (can be null), or undefined if not present
  14933. */
  14934. Engine.prototype.getExternalData = function (key) {
  14935. if (!this._externalData) {
  14936. this._externalData = new BABYLON.StringDictionary();
  14937. }
  14938. return this._externalData.get(key);
  14939. };
  14940. /**
  14941. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14942. * @param key the unique key that identifies the data
  14943. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14944. * @return the associated data, can be null if the factory returned null.
  14945. */
  14946. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14947. if (!this._externalData) {
  14948. this._externalData = new BABYLON.StringDictionary();
  14949. }
  14950. return this._externalData.getOrAddWithFactory(key, factory);
  14951. };
  14952. /**
  14953. * Remove an externaly attached data from the Engine instance
  14954. * @param key the unique key that identifies the data
  14955. * @return true if the data was successfully removed, false if it doesn't exist
  14956. */
  14957. Engine.prototype.removeExternalData = function (key) {
  14958. if (!this._externalData) {
  14959. this._externalData = new BABYLON.StringDictionary();
  14960. }
  14961. return this._externalData.remove(key);
  14962. };
  14963. Engine.prototype.unbindAllAttributes = function () {
  14964. if (this._mustWipeVertexAttributes) {
  14965. this._mustWipeVertexAttributes = false;
  14966. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14967. this._gl.disableVertexAttribArray(i);
  14968. this._vertexAttribArraysEnabled[i] = false;
  14969. this._currentBufferPointers[i].active = false;
  14970. }
  14971. return;
  14972. }
  14973. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14974. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14975. continue;
  14976. }
  14977. this._gl.disableVertexAttribArray(i);
  14978. this._vertexAttribArraysEnabled[i] = false;
  14979. this._currentBufferPointers[i].active = false;
  14980. }
  14981. };
  14982. Engine.prototype.releaseEffects = function () {
  14983. for (var name in this._compiledEffects) {
  14984. this._deleteProgram(this._compiledEffects[name]._program);
  14985. }
  14986. this._compiledEffects = {};
  14987. };
  14988. // Dispose
  14989. Engine.prototype.dispose = function () {
  14990. this.hideLoadingUI();
  14991. this.stopRenderLoop();
  14992. // Release postProcesses
  14993. while (this.postProcesses.length) {
  14994. this.postProcesses[0].dispose();
  14995. }
  14996. // Empty texture
  14997. if (this._emptyTexture) {
  14998. this._releaseTexture(this._emptyTexture);
  14999. this._emptyTexture = null;
  15000. }
  15001. if (this._emptyCubeTexture) {
  15002. this._releaseTexture(this._emptyCubeTexture);
  15003. this._emptyCubeTexture = null;
  15004. }
  15005. // Rescale PP
  15006. if (this._rescalePostProcess) {
  15007. this._rescalePostProcess.dispose();
  15008. }
  15009. // Release scenes
  15010. while (this.scenes.length) {
  15011. this.scenes[0].dispose();
  15012. }
  15013. // Release audio engine
  15014. if (Engine.audioEngine) {
  15015. Engine.audioEngine.dispose();
  15016. }
  15017. // Release effects
  15018. this.releaseEffects();
  15019. // Unbind
  15020. this.unbindAllAttributes();
  15021. this._boundUniforms = [];
  15022. if (this._dummyFramebuffer) {
  15023. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15024. }
  15025. //WebVR
  15026. this.disableVR();
  15027. // Events
  15028. if (BABYLON.Tools.IsWindowObjectExist()) {
  15029. window.removeEventListener("blur", this._onBlur);
  15030. window.removeEventListener("focus", this._onFocus);
  15031. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15032. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15033. if (this._renderingCanvas) {
  15034. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15035. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15036. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15037. if (!this._doNotHandleContextLost) {
  15038. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15039. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15040. }
  15041. }
  15042. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15043. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15044. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15045. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15046. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15047. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15048. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15049. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15050. if (this._onVrDisplayConnect) {
  15051. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15052. if (this._onVrDisplayDisconnect) {
  15053. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15054. }
  15055. if (this._onVrDisplayPresentChange) {
  15056. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15057. }
  15058. this._onVrDisplayConnect = null;
  15059. this._onVrDisplayDisconnect = null;
  15060. }
  15061. }
  15062. // Remove from Instances
  15063. var index = Engine.Instances.indexOf(this);
  15064. if (index >= 0) {
  15065. Engine.Instances.splice(index, 1);
  15066. }
  15067. this._workingCanvas = null;
  15068. this._workingContext = null;
  15069. this._currentBufferPointers = [];
  15070. this._renderingCanvas = null;
  15071. this._currentProgram = null;
  15072. this._bindedRenderFunction = null;
  15073. this.onResizeObservable.clear();
  15074. this.onCanvasBlurObservable.clear();
  15075. this.onCanvasFocusObservable.clear();
  15076. this.onCanvasPointerOutObservable.clear();
  15077. this.onBeginFrameObservable.clear();
  15078. this.onEndFrameObservable.clear();
  15079. BABYLON.Effect.ResetCache();
  15080. // Abort active requests
  15081. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15082. var request = _a[_i];
  15083. request.abort();
  15084. }
  15085. };
  15086. // Loading screen
  15087. Engine.prototype.displayLoadingUI = function () {
  15088. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15089. return;
  15090. }
  15091. var loadingScreen = this.loadingScreen;
  15092. if (loadingScreen) {
  15093. loadingScreen.displayLoadingUI();
  15094. }
  15095. };
  15096. Engine.prototype.hideLoadingUI = function () {
  15097. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15098. return;
  15099. }
  15100. var loadingScreen = this.loadingScreen;
  15101. if (loadingScreen) {
  15102. loadingScreen.hideLoadingUI();
  15103. }
  15104. };
  15105. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15106. get: function () {
  15107. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15108. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15109. return this._loadingScreen;
  15110. },
  15111. set: function (loadingScreen) {
  15112. this._loadingScreen = loadingScreen;
  15113. },
  15114. enumerable: true,
  15115. configurable: true
  15116. });
  15117. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15118. set: function (text) {
  15119. this.loadingScreen.loadingUIText = text;
  15120. },
  15121. enumerable: true,
  15122. configurable: true
  15123. });
  15124. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15125. set: function (color) {
  15126. this.loadingScreen.loadingUIBackgroundColor = color;
  15127. },
  15128. enumerable: true,
  15129. configurable: true
  15130. });
  15131. Engine.prototype.attachContextLostEvent = function (callback) {
  15132. if (this._renderingCanvas) {
  15133. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15134. }
  15135. };
  15136. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15137. if (this._renderingCanvas) {
  15138. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15139. }
  15140. };
  15141. Engine.prototype.getVertexShaderSource = function (program) {
  15142. var shaders = this._gl.getAttachedShaders(program);
  15143. if (!shaders) {
  15144. return null;
  15145. }
  15146. return this._gl.getShaderSource(shaders[0]);
  15147. };
  15148. Engine.prototype.getFragmentShaderSource = function (program) {
  15149. var shaders = this._gl.getAttachedShaders(program);
  15150. if (!shaders) {
  15151. return null;
  15152. }
  15153. return this._gl.getShaderSource(shaders[1]);
  15154. };
  15155. Engine.prototype.getError = function () {
  15156. return this._gl.getError();
  15157. };
  15158. // FPS
  15159. Engine.prototype.getFps = function () {
  15160. return this._fps;
  15161. };
  15162. Engine.prototype.getDeltaTime = function () {
  15163. return this._deltaTime;
  15164. };
  15165. Engine.prototype._measureFps = function () {
  15166. this._performanceMonitor.sampleFrame();
  15167. this._fps = this._performanceMonitor.averageFPS;
  15168. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15169. };
  15170. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15171. if (faceIndex === void 0) { faceIndex = -1; }
  15172. var gl = this._gl;
  15173. if (!this._dummyFramebuffer) {
  15174. var dummy = gl.createFramebuffer();
  15175. if (!dummy) {
  15176. throw new Error("Unable to create dummy framebuffer");
  15177. }
  15178. this._dummyFramebuffer = dummy;
  15179. }
  15180. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15181. if (faceIndex > -1) {
  15182. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15183. }
  15184. else {
  15185. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15186. }
  15187. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15188. var buffer;
  15189. switch (readType) {
  15190. case gl.UNSIGNED_BYTE:
  15191. buffer = new Uint8Array(4 * width * height);
  15192. readType = gl.UNSIGNED_BYTE;
  15193. break;
  15194. default:
  15195. buffer = new Float32Array(4 * width * height);
  15196. readType = gl.FLOAT;
  15197. break;
  15198. }
  15199. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15200. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15201. return buffer;
  15202. };
  15203. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15204. if (this._webGLVersion > 1) {
  15205. return this._caps.colorBufferFloat;
  15206. }
  15207. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15208. };
  15209. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15210. if (this._webGLVersion > 1) {
  15211. return this._caps.colorBufferFloat;
  15212. }
  15213. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15214. };
  15215. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15216. Engine.prototype._canRenderToFramebuffer = function (type) {
  15217. var gl = this._gl;
  15218. //clear existing errors
  15219. while (gl.getError() !== gl.NO_ERROR) { }
  15220. var successful = true;
  15221. var texture = gl.createTexture();
  15222. gl.bindTexture(gl.TEXTURE_2D, texture);
  15223. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15224. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15225. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15226. var fb = gl.createFramebuffer();
  15227. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15228. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15229. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15230. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15231. successful = successful && (gl.getError() === gl.NO_ERROR);
  15232. //try render by clearing frame buffer's color buffer
  15233. if (successful) {
  15234. gl.clear(gl.COLOR_BUFFER_BIT);
  15235. successful = successful && (gl.getError() === gl.NO_ERROR);
  15236. }
  15237. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15238. if (successful) {
  15239. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15240. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15241. var readFormat = gl.RGBA;
  15242. var readType = gl.UNSIGNED_BYTE;
  15243. var buffer = new Uint8Array(4);
  15244. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15245. successful = successful && (gl.getError() === gl.NO_ERROR);
  15246. }
  15247. //clean up
  15248. gl.deleteTexture(texture);
  15249. gl.deleteFramebuffer(fb);
  15250. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15251. //clear accumulated errors
  15252. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15253. return successful;
  15254. };
  15255. Engine.prototype._getWebGLTextureType = function (type) {
  15256. if (type === Engine.TEXTURETYPE_FLOAT) {
  15257. return this._gl.FLOAT;
  15258. }
  15259. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15260. // Add Half Float Constant.
  15261. return this._gl.HALF_FLOAT_OES;
  15262. }
  15263. return this._gl.UNSIGNED_BYTE;
  15264. };
  15265. ;
  15266. Engine.prototype._getInternalFormat = function (format) {
  15267. var internalFormat = this._gl.RGBA;
  15268. switch (format) {
  15269. case Engine.TEXTUREFORMAT_ALPHA:
  15270. internalFormat = this._gl.ALPHA;
  15271. break;
  15272. case Engine.TEXTUREFORMAT_LUMINANCE:
  15273. internalFormat = this._gl.LUMINANCE;
  15274. break;
  15275. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15276. internalFormat = this._gl.LUMINANCE_ALPHA;
  15277. break;
  15278. case Engine.TEXTUREFORMAT_RGB:
  15279. case Engine.TEXTUREFORMAT_RGB32F:
  15280. internalFormat = this._gl.RGB;
  15281. break;
  15282. case Engine.TEXTUREFORMAT_RGBA:
  15283. case Engine.TEXTUREFORMAT_RGBA32F:
  15284. internalFormat = this._gl.RGBA;
  15285. break;
  15286. case Engine.TEXTUREFORMAT_R32F:
  15287. internalFormat = this._gl.RED;
  15288. break;
  15289. case Engine.TEXTUREFORMAT_RG32F:
  15290. internalFormat = this._gl.RG;
  15291. break;
  15292. }
  15293. return internalFormat;
  15294. };
  15295. /** @ignore */
  15296. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15297. if (this._webGLVersion === 1) {
  15298. if (format) {
  15299. switch (format) {
  15300. case Engine.TEXTUREFORMAT_LUMINANCE:
  15301. return this._gl.LUMINANCE;
  15302. }
  15303. }
  15304. return this._gl.RGBA;
  15305. }
  15306. if (type === Engine.TEXTURETYPE_FLOAT) {
  15307. if (format) {
  15308. switch (format) {
  15309. case Engine.TEXTUREFORMAT_R32F:
  15310. return this._gl.R32F;
  15311. case Engine.TEXTUREFORMAT_RG32F:
  15312. return this._gl.RG32F;
  15313. case Engine.TEXTUREFORMAT_RGB32F:
  15314. return this._gl.RGB32F;
  15315. }
  15316. }
  15317. return this._gl.RGBA32F;
  15318. }
  15319. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15320. return this._gl.RGBA16F;
  15321. }
  15322. if (format) {
  15323. switch (format) {
  15324. case Engine.TEXTUREFORMAT_LUMINANCE:
  15325. return this._gl.LUMINANCE;
  15326. }
  15327. }
  15328. return this._gl.RGBA;
  15329. };
  15330. ;
  15331. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15332. if (type === Engine.TEXTURETYPE_FLOAT) {
  15333. return this._gl.RGBA32F;
  15334. }
  15335. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15336. return this._gl.RGBA16F;
  15337. }
  15338. return this._gl.RGBA8;
  15339. };
  15340. ;
  15341. Engine.prototype.createQuery = function () {
  15342. return this._gl.createQuery();
  15343. };
  15344. Engine.prototype.deleteQuery = function (query) {
  15345. this._gl.deleteQuery(query);
  15346. return this;
  15347. };
  15348. Engine.prototype.isQueryResultAvailable = function (query) {
  15349. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15350. };
  15351. Engine.prototype.getQueryResult = function (query) {
  15352. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15353. };
  15354. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15355. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15356. this._gl.beginQuery(glAlgorithm, query);
  15357. return this;
  15358. };
  15359. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15360. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15361. this._gl.endQuery(glAlgorithm);
  15362. return this;
  15363. };
  15364. /* Time queries */
  15365. Engine.prototype._createTimeQuery = function () {
  15366. var timerQuery = this._caps.timerQuery;
  15367. if (timerQuery.createQueryEXT) {
  15368. return timerQuery.createQueryEXT();
  15369. }
  15370. return this.createQuery();
  15371. };
  15372. Engine.prototype._deleteTimeQuery = function (query) {
  15373. var timerQuery = this._caps.timerQuery;
  15374. if (timerQuery.deleteQueryEXT) {
  15375. timerQuery.deleteQueryEXT(query);
  15376. return;
  15377. }
  15378. this.deleteQuery(query);
  15379. };
  15380. Engine.prototype._getTimeQueryResult = function (query) {
  15381. var timerQuery = this._caps.timerQuery;
  15382. if (timerQuery.getQueryObjectEXT) {
  15383. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15384. }
  15385. return this.getQueryResult(query);
  15386. };
  15387. Engine.prototype._getTimeQueryAvailability = function (query) {
  15388. var timerQuery = this._caps.timerQuery;
  15389. if (timerQuery.getQueryObjectEXT) {
  15390. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15391. }
  15392. return this.isQueryResultAvailable(query);
  15393. };
  15394. Engine.prototype.startTimeQuery = function () {
  15395. var timerQuery = this._caps.timerQuery;
  15396. if (!timerQuery) {
  15397. return null;
  15398. }
  15399. var token = new BABYLON._TimeToken();
  15400. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15401. if (this._caps.canUseTimestampForTimerQuery) {
  15402. token._startTimeQuery = this._createTimeQuery();
  15403. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15404. }
  15405. else {
  15406. if (this._currentNonTimestampToken) {
  15407. return this._currentNonTimestampToken;
  15408. }
  15409. token._timeElapsedQuery = this._createTimeQuery();
  15410. if (timerQuery.beginQueryEXT) {
  15411. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15412. }
  15413. else {
  15414. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15415. }
  15416. this._currentNonTimestampToken = token;
  15417. }
  15418. return token;
  15419. };
  15420. Engine.prototype.endTimeQuery = function (token) {
  15421. var timerQuery = this._caps.timerQuery;
  15422. if (!timerQuery || !token) {
  15423. return -1;
  15424. }
  15425. if (this._caps.canUseTimestampForTimerQuery) {
  15426. if (!token._startTimeQuery) {
  15427. return -1;
  15428. }
  15429. if (!token._endTimeQuery) {
  15430. token._endTimeQuery = this._createTimeQuery();
  15431. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15432. }
  15433. }
  15434. else if (!token._timeElapsedQueryEnded) {
  15435. if (!token._timeElapsedQuery) {
  15436. return -1;
  15437. }
  15438. if (timerQuery.endQueryEXT) {
  15439. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15440. }
  15441. else {
  15442. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15443. }
  15444. token._timeElapsedQueryEnded = true;
  15445. }
  15446. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15447. var available = false;
  15448. if (token._endTimeQuery) {
  15449. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15450. }
  15451. else if (token._timeElapsedQuery) {
  15452. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15453. }
  15454. if (available && !disjoint) {
  15455. var result = 0;
  15456. if (this._caps.canUseTimestampForTimerQuery) {
  15457. if (!token._startTimeQuery || !token._endTimeQuery) {
  15458. return -1;
  15459. }
  15460. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15461. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15462. result = timeEnd - timeStart;
  15463. this._deleteTimeQuery(token._startTimeQuery);
  15464. this._deleteTimeQuery(token._endTimeQuery);
  15465. token._startTimeQuery = null;
  15466. token._endTimeQuery = null;
  15467. }
  15468. else {
  15469. if (!token._timeElapsedQuery) {
  15470. return -1;
  15471. }
  15472. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15473. this._deleteTimeQuery(token._timeElapsedQuery);
  15474. token._timeElapsedQuery = null;
  15475. token._timeElapsedQueryEnded = false;
  15476. this._currentNonTimestampToken = null;
  15477. }
  15478. return result;
  15479. }
  15480. return -1;
  15481. };
  15482. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15483. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15484. };
  15485. // Transform feedback
  15486. Engine.prototype.createTransformFeedback = function () {
  15487. return this._gl.createTransformFeedback();
  15488. };
  15489. Engine.prototype.deleteTransformFeedback = function (value) {
  15490. this._gl.deleteTransformFeedback(value);
  15491. };
  15492. Engine.prototype.bindTransformFeedback = function (value) {
  15493. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15494. };
  15495. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15496. if (usePoints === void 0) { usePoints = true; }
  15497. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15498. };
  15499. Engine.prototype.endTransformFeedback = function () {
  15500. this._gl.endTransformFeedback();
  15501. };
  15502. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15503. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15504. };
  15505. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15506. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15507. };
  15508. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15509. var _this = this;
  15510. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15511. this._activeRequests.push(request);
  15512. request.onCompleteObservable.add(function (request) {
  15513. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15514. });
  15515. return request;
  15516. };
  15517. /** @ignore */
  15518. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15519. var _this = this;
  15520. return new Promise(function (resolve, reject) {
  15521. _this._loadFile(url, function (data) {
  15522. resolve(data);
  15523. }, undefined, database, useArrayBuffer, function (request, exception) {
  15524. reject(exception);
  15525. });
  15526. });
  15527. };
  15528. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15529. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15530. var onload = function (data) {
  15531. loadedFiles[index] = data;
  15532. loadedFiles._internalCount++;
  15533. if (loadedFiles._internalCount === 6) {
  15534. onfinish(loadedFiles);
  15535. }
  15536. };
  15537. var onerror = function (request, exception) {
  15538. if (onErrorCallBack && request) {
  15539. onErrorCallBack(request.status + " " + request.statusText, exception);
  15540. }
  15541. };
  15542. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15543. };
  15544. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15545. if (onError === void 0) { onError = null; }
  15546. var loadedFiles = [];
  15547. loadedFiles._internalCount = 0;
  15548. for (var index = 0; index < 6; index++) {
  15549. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15550. }
  15551. };
  15552. // Statics
  15553. Engine.isSupported = function () {
  15554. try {
  15555. var tempcanvas = document.createElement("canvas");
  15556. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15557. return gl != null && !!window.WebGLRenderingContext;
  15558. }
  15559. catch (e) {
  15560. return false;
  15561. }
  15562. };
  15563. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15564. Engine.ExceptionList = [
  15565. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15566. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15567. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15568. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15569. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15570. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15571. ];
  15572. Engine.Instances = new Array();
  15573. // Const statics
  15574. Engine._ALPHA_DISABLE = 0;
  15575. Engine._ALPHA_ADD = 1;
  15576. Engine._ALPHA_COMBINE = 2;
  15577. Engine._ALPHA_SUBTRACT = 3;
  15578. Engine._ALPHA_MULTIPLY = 4;
  15579. Engine._ALPHA_MAXIMIZED = 5;
  15580. Engine._ALPHA_ONEONE = 6;
  15581. Engine._ALPHA_PREMULTIPLIED = 7;
  15582. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15583. Engine._ALPHA_INTERPOLATE = 9;
  15584. Engine._ALPHA_SCREENMODE = 10;
  15585. Engine._DELAYLOADSTATE_NONE = 0;
  15586. Engine._DELAYLOADSTATE_LOADED = 1;
  15587. Engine._DELAYLOADSTATE_LOADING = 2;
  15588. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15589. Engine._TEXTUREFORMAT_ALPHA = 0;
  15590. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15591. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15592. Engine._TEXTUREFORMAT_RGB = 4;
  15593. Engine._TEXTUREFORMAT_RGBA = 5;
  15594. Engine._TEXTUREFORMAT_R32F = 6;
  15595. Engine._TEXTUREFORMAT_RG32F = 7;
  15596. Engine._TEXTUREFORMAT_RGB32F = 8;
  15597. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15598. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15599. Engine._TEXTURETYPE_FLOAT = 1;
  15600. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15601. // Depht or Stencil test Constants.
  15602. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15603. 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.
  15604. 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.
  15605. 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.
  15606. 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.
  15607. 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.
  15608. 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.
  15609. 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.
  15610. // Stencil Actions Constants.
  15611. Engine._KEEP = 0x1E00;
  15612. Engine._REPLACE = 0x1E01;
  15613. Engine._INCR = 0x1E02;
  15614. Engine._DECR = 0x1E03;
  15615. Engine._INVERT = 0x150A;
  15616. Engine._INCR_WRAP = 0x8507;
  15617. Engine._DECR_WRAP = 0x8508;
  15618. // Texture rescaling mode
  15619. Engine._SCALEMODE_FLOOR = 1;
  15620. Engine._SCALEMODE_NEAREST = 2;
  15621. Engine._SCALEMODE_CEILING = 3;
  15622. // Updatable statics so stick with vars here
  15623. Engine.CollisionsEpsilon = 0.001;
  15624. Engine.CodeRepository = "src/";
  15625. Engine.ShadersRepository = "src/Shaders/";
  15626. return Engine;
  15627. }());
  15628. BABYLON.Engine = Engine;
  15629. })(BABYLON || (BABYLON = {}));
  15630. //# sourceMappingURL=babylon.engine.js.map
  15631. "use strict";
  15632. var BABYLON;
  15633. (function (BABYLON) {
  15634. /**
  15635. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15636. */
  15637. var Node = /** @class */ (function () {
  15638. /**
  15639. * Creates a new Node
  15640. * @param {string} name - the name and id to be given to this node
  15641. * @param {BABYLON.Scene} the scene this node will be added to
  15642. */
  15643. function Node(name, scene) {
  15644. if (scene === void 0) { scene = null; }
  15645. /**
  15646. * Gets or sets a string used to store user defined state for the node
  15647. */
  15648. this.state = "";
  15649. /**
  15650. * Gets or sets an object used to store user defined information for the node
  15651. */
  15652. this.metadata = null;
  15653. /**
  15654. * Gets or sets a boolean used to define if the node must be serialized
  15655. */
  15656. this.doNotSerialize = false;
  15657. /** @ignore */
  15658. this._isDisposed = false;
  15659. /**
  15660. * Gets a list of Animations associated with the node
  15661. */
  15662. this.animations = new Array();
  15663. this._ranges = {};
  15664. this._isEnabled = true;
  15665. this._isReady = true;
  15666. /** @ignore */
  15667. this._currentRenderId = -1;
  15668. this._parentRenderId = -1;
  15669. this._childRenderId = -1;
  15670. this._animationPropertiesOverride = null;
  15671. /**
  15672. * An event triggered when the mesh is disposed
  15673. */
  15674. this.onDisposeObservable = new BABYLON.Observable();
  15675. // Behaviors
  15676. this._behaviors = new Array();
  15677. this.name = name;
  15678. this.id = name;
  15679. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15680. this.uniqueId = this._scene.getUniqueId();
  15681. this._initCache();
  15682. }
  15683. /**
  15684. * Gets a boolean indicating if the node has been disposed
  15685. * @returns true if the node was disposed
  15686. */
  15687. Node.prototype.isDisposed = function () {
  15688. return this._isDisposed;
  15689. };
  15690. Object.defineProperty(Node.prototype, "parent", {
  15691. get: function () {
  15692. return this._parentNode;
  15693. },
  15694. /**
  15695. * Gets or sets the parent of the node
  15696. */
  15697. set: function (parent) {
  15698. if (this._parentNode === parent) {
  15699. return;
  15700. }
  15701. // Remove self from list of children of parent
  15702. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15703. var index = this._parentNode._children.indexOf(this);
  15704. if (index !== -1) {
  15705. this._parentNode._children.splice(index, 1);
  15706. }
  15707. }
  15708. // Store new parent
  15709. this._parentNode = parent;
  15710. // Add as child to new parent
  15711. if (this._parentNode) {
  15712. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15713. this._parentNode._children = new Array();
  15714. }
  15715. this._parentNode._children.push(this);
  15716. }
  15717. },
  15718. enumerable: true,
  15719. configurable: true
  15720. });
  15721. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15722. /**
  15723. * Gets or sets the animation properties override
  15724. */
  15725. get: function () {
  15726. return this._animationPropertiesOverride;
  15727. },
  15728. set: function (value) {
  15729. this._animationPropertiesOverride = value;
  15730. },
  15731. enumerable: true,
  15732. configurable: true
  15733. });
  15734. /**
  15735. * Gets a string idenfifying the name of the class
  15736. * @returns "Node" string
  15737. */
  15738. Node.prototype.getClassName = function () {
  15739. return "Node";
  15740. };
  15741. Object.defineProperty(Node.prototype, "onDispose", {
  15742. /**
  15743. * Sets a callback that will be raised when the node will be disposed
  15744. */
  15745. set: function (callback) {
  15746. if (this._onDisposeObserver) {
  15747. this.onDisposeObservable.remove(this._onDisposeObserver);
  15748. }
  15749. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15750. },
  15751. enumerable: true,
  15752. configurable: true
  15753. });
  15754. /**
  15755. * Gets the scene of the node
  15756. * @returns a {BABYLON.Scene}
  15757. */
  15758. Node.prototype.getScene = function () {
  15759. return this._scene;
  15760. };
  15761. /**
  15762. * Gets the engine of the node
  15763. * @returns a {BABYLON.Engine}
  15764. */
  15765. Node.prototype.getEngine = function () {
  15766. return this._scene.getEngine();
  15767. };
  15768. /**
  15769. * Attach a behavior to the node
  15770. * @see http://doc.babylonjs.com/features/behaviour
  15771. * @param behavior defines the behavior to attach
  15772. * @returns the current Node
  15773. */
  15774. Node.prototype.addBehavior = function (behavior) {
  15775. var _this = this;
  15776. var index = this._behaviors.indexOf(behavior);
  15777. if (index !== -1) {
  15778. return this;
  15779. }
  15780. behavior.init();
  15781. if (this._scene.isLoading) {
  15782. // We defer the attach when the scene will be loaded
  15783. var observer = this._scene.onDataLoadedObservable.add(function () {
  15784. behavior.attach(_this);
  15785. setTimeout(function () {
  15786. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15787. _this._scene.onDataLoadedObservable.remove(observer);
  15788. }, 0);
  15789. });
  15790. }
  15791. else {
  15792. behavior.attach(this);
  15793. }
  15794. this._behaviors.push(behavior);
  15795. return this;
  15796. };
  15797. /**
  15798. * Remove an attached behavior
  15799. * @see http://doc.babylonjs.com/features/behaviour
  15800. * @param behavior defines the behavior to attach
  15801. * @returns the current Node
  15802. */
  15803. Node.prototype.removeBehavior = function (behavior) {
  15804. var index = this._behaviors.indexOf(behavior);
  15805. if (index === -1) {
  15806. return this;
  15807. }
  15808. this._behaviors[index].detach();
  15809. this._behaviors.splice(index, 1);
  15810. return this;
  15811. };
  15812. Object.defineProperty(Node.prototype, "behaviors", {
  15813. /**
  15814. * Gets the list of attached behaviors
  15815. * @see http://doc.babylonjs.com/features/behaviour
  15816. */
  15817. get: function () {
  15818. return this._behaviors;
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. /**
  15824. * Gets an attached behavior by name
  15825. * @param name defines the name of the behavior to look for
  15826. * @see http://doc.babylonjs.com/features/behaviour
  15827. * @returns null if behavior was not found else the requested behavior
  15828. */
  15829. Node.prototype.getBehaviorByName = function (name) {
  15830. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15831. var behavior = _a[_i];
  15832. if (behavior.name === name) {
  15833. return behavior;
  15834. }
  15835. }
  15836. return null;
  15837. };
  15838. /**
  15839. * Returns the world matrix of the node
  15840. * @returns a matrix containing the node's world matrix
  15841. */
  15842. Node.prototype.getWorldMatrix = function () {
  15843. return BABYLON.Matrix.Identity();
  15844. };
  15845. // override it in derived class if you add new variables to the cache
  15846. // and call the parent class method
  15847. /** @ignore */
  15848. Node.prototype._initCache = function () {
  15849. this._cache = {};
  15850. this._cache.parent = undefined;
  15851. };
  15852. /** @ignore */
  15853. Node.prototype.updateCache = function (force) {
  15854. if (!force && this.isSynchronized())
  15855. return;
  15856. this._cache.parent = this.parent;
  15857. this._updateCache();
  15858. };
  15859. // override it in derived class if you add new variables to the cache
  15860. // and call the parent class method if !ignoreParentClass
  15861. /** @ignore */
  15862. Node.prototype._updateCache = function (ignoreParentClass) {
  15863. };
  15864. // override it in derived class if you add new variables to the cache
  15865. /** @ignore */
  15866. Node.prototype._isSynchronized = function () {
  15867. return true;
  15868. };
  15869. /** @ignore */
  15870. Node.prototype._markSyncedWithParent = function () {
  15871. if (this.parent) {
  15872. this._parentRenderId = this.parent._childRenderId;
  15873. }
  15874. };
  15875. /** @ignore */
  15876. Node.prototype.isSynchronizedWithParent = function () {
  15877. if (!this.parent) {
  15878. return true;
  15879. }
  15880. if (this._parentRenderId !== this.parent._childRenderId) {
  15881. return false;
  15882. }
  15883. return this.parent.isSynchronized();
  15884. };
  15885. /** @ignore */
  15886. Node.prototype.isSynchronized = function (updateCache) {
  15887. var check = this.hasNewParent();
  15888. check = check || !this.isSynchronizedWithParent();
  15889. check = check || !this._isSynchronized();
  15890. if (updateCache)
  15891. this.updateCache(true);
  15892. return !check;
  15893. };
  15894. /** @ignore */
  15895. Node.prototype.hasNewParent = function (update) {
  15896. if (this._cache.parent === this.parent)
  15897. return false;
  15898. if (update)
  15899. this._cache.parent = this.parent;
  15900. return true;
  15901. };
  15902. /**
  15903. * Is this node ready to be used/rendered
  15904. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15905. * @return true if the node is ready
  15906. */
  15907. Node.prototype.isReady = function (completeCheck) {
  15908. if (completeCheck === void 0) { completeCheck = false; }
  15909. return this._isReady;
  15910. };
  15911. /**
  15912. * Is this node enabled?
  15913. * 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
  15914. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15915. * @return whether this node (and its parent) is enabled
  15916. */
  15917. Node.prototype.isEnabled = function (checkAncestors) {
  15918. if (checkAncestors === void 0) { checkAncestors = true; }
  15919. if (checkAncestors === false) {
  15920. return this._isEnabled;
  15921. }
  15922. if (this._isEnabled === false) {
  15923. return false;
  15924. }
  15925. if (this.parent !== undefined && this.parent !== null) {
  15926. return this.parent.isEnabled(checkAncestors);
  15927. }
  15928. return true;
  15929. };
  15930. /**
  15931. * Set the enabled state of this node
  15932. * @param value defines the new enabled state
  15933. */
  15934. Node.prototype.setEnabled = function (value) {
  15935. this._isEnabled = value;
  15936. };
  15937. /**
  15938. * Is this node a descendant of the given node?
  15939. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15940. * @param ancestor defines the parent node to inspect
  15941. * @returns a boolean indicating if this node is a descendant of the given node
  15942. */
  15943. Node.prototype.isDescendantOf = function (ancestor) {
  15944. if (this.parent) {
  15945. if (this.parent === ancestor) {
  15946. return true;
  15947. }
  15948. return this.parent.isDescendantOf(ancestor);
  15949. }
  15950. return false;
  15951. };
  15952. /** @ignore */
  15953. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15954. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15955. if (!this._children) {
  15956. return;
  15957. }
  15958. for (var index = 0; index < this._children.length; index++) {
  15959. var item = this._children[index];
  15960. if (!predicate || predicate(item)) {
  15961. results.push(item);
  15962. }
  15963. if (!directDescendantsOnly) {
  15964. item._getDescendants(results, false, predicate);
  15965. }
  15966. }
  15967. };
  15968. /**
  15969. * Will return all nodes that have this node as ascendant
  15970. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15971. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15972. * @return all children nodes of all types
  15973. */
  15974. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15975. var results = new Array();
  15976. this._getDescendants(results, directDescendantsOnly, predicate);
  15977. return results;
  15978. };
  15979. /**
  15980. * Get all child-meshes of this node
  15981. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15982. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15983. * @returns an array of {BABYLON.AbstractMesh}
  15984. */
  15985. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15986. var results = [];
  15987. this._getDescendants(results, directDescendantsOnly, function (node) {
  15988. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15989. });
  15990. return results;
  15991. };
  15992. /**
  15993. * Get all child-transformNodes of this node
  15994. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15995. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15996. * @returns an array of {BABYLON.TransformNode}
  15997. */
  15998. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15999. var results = [];
  16000. this._getDescendants(results, directDescendantsOnly, function (node) {
  16001. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16002. });
  16003. return results;
  16004. };
  16005. /**
  16006. * Get all direct children of this node
  16007. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16008. * @returns an array of {BABYLON.Node}
  16009. */
  16010. Node.prototype.getChildren = function (predicate) {
  16011. return this.getDescendants(true, predicate);
  16012. };
  16013. /** @ignore */
  16014. Node.prototype._setReady = function (state) {
  16015. if (state === this._isReady) {
  16016. return;
  16017. }
  16018. if (!state) {
  16019. this._isReady = false;
  16020. return;
  16021. }
  16022. if (this.onReady) {
  16023. this.onReady(this);
  16024. }
  16025. this._isReady = true;
  16026. };
  16027. /**
  16028. * Get an animation by name
  16029. * @param name defines the name of the animation to look for
  16030. * @returns null if not found else the requested animation
  16031. */
  16032. Node.prototype.getAnimationByName = function (name) {
  16033. for (var i = 0; i < this.animations.length; i++) {
  16034. var animation = this.animations[i];
  16035. if (animation.name === name) {
  16036. return animation;
  16037. }
  16038. }
  16039. return null;
  16040. };
  16041. /**
  16042. * Creates an animation range for this node
  16043. * @param name defines the name of the range
  16044. * @param from defines the starting key
  16045. * @param to defines the end key
  16046. */
  16047. Node.prototype.createAnimationRange = function (name, from, to) {
  16048. // check name not already in use
  16049. if (!this._ranges[name]) {
  16050. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16051. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16052. if (this.animations[i]) {
  16053. this.animations[i].createRange(name, from, to);
  16054. }
  16055. }
  16056. }
  16057. };
  16058. /**
  16059. * Delete a specific animation range
  16060. * @param name defines the name of the range to delete
  16061. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16062. */
  16063. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16064. if (deleteFrames === void 0) { deleteFrames = true; }
  16065. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16066. if (this.animations[i]) {
  16067. this.animations[i].deleteRange(name, deleteFrames);
  16068. }
  16069. }
  16070. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16071. };
  16072. /**
  16073. * Get an animation range by name
  16074. * @param name defines the name of the animation range to look for
  16075. * @returns null if not found else the requested animation range
  16076. */
  16077. Node.prototype.getAnimationRange = function (name) {
  16078. return this._ranges[name];
  16079. };
  16080. /**
  16081. * Will start the animation sequence
  16082. * @param name defines the range frames for animation sequence
  16083. * @param loop defines if the animation should loop (false by default)
  16084. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16085. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16086. * @returns the object created for this animation. If range does not exist, it will return null
  16087. */
  16088. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16089. var range = this.getAnimationRange(name);
  16090. if (!range) {
  16091. return null;
  16092. }
  16093. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16094. };
  16095. /**
  16096. * Serialize animation ranges into a JSON compatible object
  16097. * @returns serialization object
  16098. */
  16099. Node.prototype.serializeAnimationRanges = function () {
  16100. var serializationRanges = [];
  16101. for (var name in this._ranges) {
  16102. var localRange = this._ranges[name];
  16103. if (!localRange) {
  16104. continue;
  16105. }
  16106. var range = {};
  16107. range.name = name;
  16108. range.from = localRange.from;
  16109. range.to = localRange.to;
  16110. serializationRanges.push(range);
  16111. }
  16112. return serializationRanges;
  16113. };
  16114. /**
  16115. * Computes the world matrix of the node
  16116. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16117. * @returns the world matrix
  16118. */
  16119. Node.prototype.computeWorldMatrix = function (force) {
  16120. return BABYLON.Matrix.Identity();
  16121. };
  16122. /**
  16123. * Releases resources associated with this node.
  16124. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16125. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16126. */
  16127. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16128. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16129. if (!doNotRecurse) {
  16130. var nodes = this.getDescendants(true);
  16131. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16132. var node = nodes_1[_i];
  16133. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16134. }
  16135. }
  16136. else {
  16137. var transformNodes = this.getChildTransformNodes(true);
  16138. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16139. var transformNode = transformNodes_1[_a];
  16140. transformNode.parent = null;
  16141. transformNode.computeWorldMatrix(true);
  16142. }
  16143. }
  16144. this.parent = null;
  16145. // Callback
  16146. this.onDisposeObservable.notifyObservers(this);
  16147. this.onDisposeObservable.clear();
  16148. // Behaviors
  16149. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16150. var behavior = _c[_b];
  16151. behavior.detach();
  16152. }
  16153. this._behaviors = [];
  16154. this._isDisposed = true;
  16155. };
  16156. /**
  16157. * Parse animation range data from a serialization object and store them into a given node
  16158. * @param node defines where to store the animation ranges
  16159. * @param parsedNode defines the serialization object to read data from
  16160. * @param scene defines the hosting scene
  16161. */
  16162. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16163. if (parsedNode.ranges) {
  16164. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16165. var data = parsedNode.ranges[index];
  16166. node.createAnimationRange(data.name, data.from, data.to);
  16167. }
  16168. }
  16169. };
  16170. __decorate([
  16171. BABYLON.serialize()
  16172. ], Node.prototype, "name", void 0);
  16173. __decorate([
  16174. BABYLON.serialize()
  16175. ], Node.prototype, "id", void 0);
  16176. __decorate([
  16177. BABYLON.serialize()
  16178. ], Node.prototype, "uniqueId", void 0);
  16179. __decorate([
  16180. BABYLON.serialize()
  16181. ], Node.prototype, "state", void 0);
  16182. __decorate([
  16183. BABYLON.serialize()
  16184. ], Node.prototype, "metadata", void 0);
  16185. return Node;
  16186. }());
  16187. BABYLON.Node = Node;
  16188. })(BABYLON || (BABYLON = {}));
  16189. //# sourceMappingURL=babylon.node.js.map
  16190. "use strict";
  16191. var BABYLON;
  16192. (function (BABYLON) {
  16193. var BoundingSphere = /** @class */ (function () {
  16194. function BoundingSphere(minimum, maximum) {
  16195. this.minimum = minimum;
  16196. this.maximum = maximum;
  16197. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16198. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16199. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16200. this.radius = distance * 0.5;
  16201. this.centerWorld = BABYLON.Vector3.Zero();
  16202. this._update(BABYLON.Matrix.Identity());
  16203. }
  16204. // Methods
  16205. BoundingSphere.prototype._update = function (world) {
  16206. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16207. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16208. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16209. };
  16210. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16211. for (var i = 0; i < 6; i++) {
  16212. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16213. return false;
  16214. }
  16215. return true;
  16216. };
  16217. BoundingSphere.prototype.intersectsPoint = function (point) {
  16218. var x = this.centerWorld.x - point.x;
  16219. var y = this.centerWorld.y - point.y;
  16220. var z = this.centerWorld.z - point.z;
  16221. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16222. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16223. return false;
  16224. return true;
  16225. };
  16226. // Statics
  16227. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16228. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16229. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16230. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16231. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16232. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16233. return false;
  16234. return true;
  16235. };
  16236. return BoundingSphere;
  16237. }());
  16238. BABYLON.BoundingSphere = BoundingSphere;
  16239. })(BABYLON || (BABYLON = {}));
  16240. //# sourceMappingURL=babylon.boundingSphere.js.map
  16241. "use strict";
  16242. var BABYLON;
  16243. (function (BABYLON) {
  16244. var BoundingBox = /** @class */ (function () {
  16245. function BoundingBox(minimum, maximum) {
  16246. this.minimum = minimum;
  16247. this.maximum = maximum;
  16248. this.vectors = new Array();
  16249. this.vectorsWorld = new Array();
  16250. // Bounding vectors
  16251. this.vectors.push(this.minimum.clone());
  16252. this.vectors.push(this.maximum.clone());
  16253. this.vectors.push(this.minimum.clone());
  16254. this.vectors[2].x = this.maximum.x;
  16255. this.vectors.push(this.minimum.clone());
  16256. this.vectors[3].y = this.maximum.y;
  16257. this.vectors.push(this.minimum.clone());
  16258. this.vectors[4].z = this.maximum.z;
  16259. this.vectors.push(this.maximum.clone());
  16260. this.vectors[5].z = this.minimum.z;
  16261. this.vectors.push(this.maximum.clone());
  16262. this.vectors[6].x = this.minimum.x;
  16263. this.vectors.push(this.maximum.clone());
  16264. this.vectors[7].y = this.minimum.y;
  16265. // OBB
  16266. this.center = this.maximum.add(this.minimum).scale(0.5);
  16267. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16268. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16269. // World
  16270. for (var index = 0; index < this.vectors.length; index++) {
  16271. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16272. }
  16273. this.minimumWorld = BABYLON.Vector3.Zero();
  16274. this.maximumWorld = BABYLON.Vector3.Zero();
  16275. this.centerWorld = BABYLON.Vector3.Zero();
  16276. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16277. this._update(BABYLON.Matrix.Identity());
  16278. }
  16279. // Methods
  16280. BoundingBox.prototype.getWorldMatrix = function () {
  16281. return this._worldMatrix;
  16282. };
  16283. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16284. this._worldMatrix.copyFrom(matrix);
  16285. return this;
  16286. };
  16287. BoundingBox.prototype._update = function (world) {
  16288. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16289. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16290. for (var index = 0; index < this.vectors.length; index++) {
  16291. var v = this.vectorsWorld[index];
  16292. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16293. if (v.x < this.minimumWorld.x)
  16294. this.minimumWorld.x = v.x;
  16295. if (v.y < this.minimumWorld.y)
  16296. this.minimumWorld.y = v.y;
  16297. if (v.z < this.minimumWorld.z)
  16298. this.minimumWorld.z = v.z;
  16299. if (v.x > this.maximumWorld.x)
  16300. this.maximumWorld.x = v.x;
  16301. if (v.y > this.maximumWorld.y)
  16302. this.maximumWorld.y = v.y;
  16303. if (v.z > this.maximumWorld.z)
  16304. this.maximumWorld.z = v.z;
  16305. }
  16306. // Extend
  16307. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16308. this.extendSizeWorld.scaleInPlace(0.5);
  16309. // OBB
  16310. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16311. this.centerWorld.scaleInPlace(0.5);
  16312. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16313. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16314. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16315. this._worldMatrix = world;
  16316. };
  16317. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16318. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16319. };
  16320. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16321. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16322. };
  16323. BoundingBox.prototype.intersectsPoint = function (point) {
  16324. var delta = -BABYLON.Epsilon;
  16325. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16326. return false;
  16327. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16328. return false;
  16329. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16330. return false;
  16331. return true;
  16332. };
  16333. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16334. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16335. };
  16336. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16337. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16338. return false;
  16339. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16340. return false;
  16341. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16342. return false;
  16343. return true;
  16344. };
  16345. // Statics
  16346. BoundingBox.Intersects = function (box0, box1) {
  16347. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16348. return false;
  16349. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16350. return false;
  16351. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16352. return false;
  16353. return true;
  16354. };
  16355. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16356. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16357. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16358. return (num <= (sphereRadius * sphereRadius));
  16359. };
  16360. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16361. for (var p = 0; p < 6; p++) {
  16362. for (var i = 0; i < 8; i++) {
  16363. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16364. return false;
  16365. }
  16366. }
  16367. }
  16368. return true;
  16369. };
  16370. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16371. for (var p = 0; p < 6; p++) {
  16372. var inCount = 8;
  16373. for (var i = 0; i < 8; i++) {
  16374. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16375. --inCount;
  16376. }
  16377. else {
  16378. break;
  16379. }
  16380. }
  16381. if (inCount === 0)
  16382. return false;
  16383. }
  16384. return true;
  16385. };
  16386. return BoundingBox;
  16387. }());
  16388. BABYLON.BoundingBox = BoundingBox;
  16389. })(BABYLON || (BABYLON = {}));
  16390. //# sourceMappingURL=babylon.boundingBox.js.map
  16391. "use strict";
  16392. var BABYLON;
  16393. (function (BABYLON) {
  16394. var computeBoxExtents = function (axis, box) {
  16395. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16396. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16397. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16398. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16399. var r = r0 + r1 + r2;
  16400. return {
  16401. min: p - r,
  16402. max: p + r
  16403. };
  16404. };
  16405. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16406. var axisOverlap = function (axis, box0, box1) {
  16407. var result0 = computeBoxExtents(axis, box0);
  16408. var result1 = computeBoxExtents(axis, box1);
  16409. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16410. };
  16411. var BoundingInfo = /** @class */ (function () {
  16412. function BoundingInfo(minimum, maximum) {
  16413. this.minimum = minimum;
  16414. this.maximum = maximum;
  16415. this._isLocked = false;
  16416. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16417. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16418. }
  16419. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16420. get: function () {
  16421. return this._isLocked;
  16422. },
  16423. set: function (value) {
  16424. this._isLocked = value;
  16425. },
  16426. enumerable: true,
  16427. configurable: true
  16428. });
  16429. // Methods
  16430. BoundingInfo.prototype.update = function (world) {
  16431. if (this._isLocked) {
  16432. return;
  16433. }
  16434. this.boundingBox._update(world);
  16435. this.boundingSphere._update(world);
  16436. };
  16437. /**
  16438. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16439. * @param center New center of the bounding info
  16440. * @param extend New extend of the bounding info
  16441. */
  16442. BoundingInfo.prototype.centerOn = function (center, extend) {
  16443. this.minimum = center.subtract(extend);
  16444. this.maximum = center.add(extend);
  16445. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16446. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16447. return this;
  16448. };
  16449. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16450. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16451. return false;
  16452. return this.boundingBox.isInFrustum(frustumPlanes);
  16453. };
  16454. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16455. /**
  16456. * Gets the world distance between the min and max points of the bounding box
  16457. */
  16458. get: function () {
  16459. var boundingBox = this.boundingBox;
  16460. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16461. return size.length();
  16462. },
  16463. enumerable: true,
  16464. configurable: true
  16465. });
  16466. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16467. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16468. };
  16469. BoundingInfo.prototype._checkCollision = function (collider) {
  16470. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16471. };
  16472. BoundingInfo.prototype.intersectsPoint = function (point) {
  16473. if (!this.boundingSphere.centerWorld) {
  16474. return false;
  16475. }
  16476. if (!this.boundingSphere.intersectsPoint(point)) {
  16477. return false;
  16478. }
  16479. if (!this.boundingBox.intersectsPoint(point)) {
  16480. return false;
  16481. }
  16482. return true;
  16483. };
  16484. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16485. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16486. return false;
  16487. }
  16488. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16489. return false;
  16490. }
  16491. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16492. return false;
  16493. }
  16494. if (!precise) {
  16495. return true;
  16496. }
  16497. var box0 = this.boundingBox;
  16498. var box1 = boundingInfo.boundingBox;
  16499. if (!axisOverlap(box0.directions[0], box0, box1))
  16500. return false;
  16501. if (!axisOverlap(box0.directions[1], box0, box1))
  16502. return false;
  16503. if (!axisOverlap(box0.directions[2], box0, box1))
  16504. return false;
  16505. if (!axisOverlap(box1.directions[0], box0, box1))
  16506. return false;
  16507. if (!axisOverlap(box1.directions[1], box0, box1))
  16508. return false;
  16509. if (!axisOverlap(box1.directions[2], box0, box1))
  16510. return false;
  16511. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16512. return false;
  16513. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16514. return false;
  16515. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16516. return false;
  16517. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16518. return false;
  16519. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16520. return false;
  16521. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16522. return false;
  16523. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16524. return false;
  16525. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16526. return false;
  16527. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16528. return false;
  16529. return true;
  16530. };
  16531. return BoundingInfo;
  16532. }());
  16533. BABYLON.BoundingInfo = BoundingInfo;
  16534. })(BABYLON || (BABYLON = {}));
  16535. //# sourceMappingURL=babylon.boundingInfo.js.map
  16536. "use strict";
  16537. var BABYLON;
  16538. (function (BABYLON) {
  16539. var TransformNode = /** @class */ (function (_super) {
  16540. __extends(TransformNode, _super);
  16541. function TransformNode(name, scene, isPure) {
  16542. if (scene === void 0) { scene = null; }
  16543. if (isPure === void 0) { isPure = true; }
  16544. var _this = _super.call(this, name, scene) || this;
  16545. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16546. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16547. _this._up = new BABYLON.Vector3(0, 1, 0);
  16548. _this._right = new BABYLON.Vector3(1, 0, 0);
  16549. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16550. // Properties
  16551. _this._rotation = BABYLON.Vector3.Zero();
  16552. _this._scaling = BABYLON.Vector3.One();
  16553. _this._isDirty = false;
  16554. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16555. _this.scalingDeterminant = 1;
  16556. _this.infiniteDistance = false;
  16557. _this.position = BABYLON.Vector3.Zero();
  16558. _this._localWorld = BABYLON.Matrix.Zero();
  16559. _this._worldMatrix = BABYLON.Matrix.Zero();
  16560. _this._worldMatrixDeterminant = 0;
  16561. _this._absolutePosition = BABYLON.Vector3.Zero();
  16562. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16563. _this._postMultiplyPivotMatrix = false;
  16564. _this._isWorldMatrixFrozen = false;
  16565. /**
  16566. * An event triggered after the world matrix is updated
  16567. */
  16568. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16569. _this._nonUniformScaling = false;
  16570. if (isPure) {
  16571. _this.getScene().addTransformNode(_this);
  16572. }
  16573. return _this;
  16574. }
  16575. /**
  16576. * Gets a string idenfifying the name of the class
  16577. * @returns "TransformNode" string
  16578. */
  16579. TransformNode.prototype.getClassName = function () {
  16580. return "TransformNode";
  16581. };
  16582. Object.defineProperty(TransformNode.prototype, "rotation", {
  16583. /**
  16584. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16585. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16586. * Default : (0.0, 0.0, 0.0)
  16587. */
  16588. get: function () {
  16589. return this._rotation;
  16590. },
  16591. set: function (newRotation) {
  16592. this._rotation = newRotation;
  16593. },
  16594. enumerable: true,
  16595. configurable: true
  16596. });
  16597. Object.defineProperty(TransformNode.prototype, "scaling", {
  16598. /**
  16599. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16600. * Default : (1.0, 1.0, 1.0)
  16601. */
  16602. get: function () {
  16603. return this._scaling;
  16604. },
  16605. /**
  16606. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16607. * Default : (1.0, 1.0, 1.0)
  16608. */
  16609. set: function (newScaling) {
  16610. this._scaling = newScaling;
  16611. },
  16612. enumerable: true,
  16613. configurable: true
  16614. });
  16615. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16616. /**
  16617. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16618. * It's null by default.
  16619. * 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)
  16620. */
  16621. get: function () {
  16622. return this._rotationQuaternion;
  16623. },
  16624. set: function (quaternion) {
  16625. this._rotationQuaternion = quaternion;
  16626. //reset the rotation vector.
  16627. if (quaternion && this.rotation.length()) {
  16628. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16629. }
  16630. },
  16631. enumerable: true,
  16632. configurable: true
  16633. });
  16634. Object.defineProperty(TransformNode.prototype, "forward", {
  16635. /**
  16636. * The forward direction of that transform in world space.
  16637. */
  16638. get: function () {
  16639. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16640. },
  16641. enumerable: true,
  16642. configurable: true
  16643. });
  16644. Object.defineProperty(TransformNode.prototype, "up", {
  16645. /**
  16646. * The up direction of that transform in world space.
  16647. */
  16648. get: function () {
  16649. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16650. },
  16651. enumerable: true,
  16652. configurable: true
  16653. });
  16654. Object.defineProperty(TransformNode.prototype, "right", {
  16655. /**
  16656. * The right direction of that transform in world space.
  16657. */
  16658. get: function () {
  16659. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16660. },
  16661. enumerable: true,
  16662. configurable: true
  16663. });
  16664. /**
  16665. * Returns the latest update of the World matrix
  16666. * Returns a Matrix.
  16667. */
  16668. TransformNode.prototype.getWorldMatrix = function () {
  16669. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16670. this.computeWorldMatrix();
  16671. }
  16672. return this._worldMatrix;
  16673. };
  16674. /**
  16675. * Returns the latest update of the World matrix determinant.
  16676. */
  16677. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16678. return this._worldMatrixDeterminant;
  16679. };
  16680. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16681. /**
  16682. * Returns directly the latest state of the mesh World matrix.
  16683. * A Matrix is returned.
  16684. */
  16685. get: function () {
  16686. return this._worldMatrix;
  16687. },
  16688. enumerable: true,
  16689. configurable: true
  16690. });
  16691. /**
  16692. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16693. * Returns the TransformNode.
  16694. */
  16695. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16696. this._poseMatrix.copyFrom(matrix);
  16697. return this;
  16698. };
  16699. /**
  16700. * Returns the mesh Pose matrix.
  16701. * Returned object : Matrix
  16702. */
  16703. TransformNode.prototype.getPoseMatrix = function () {
  16704. return this._poseMatrix;
  16705. };
  16706. TransformNode.prototype._isSynchronized = function () {
  16707. if (this._isDirty) {
  16708. return false;
  16709. }
  16710. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16711. return false;
  16712. if (this._cache.pivotMatrixUpdated) {
  16713. return false;
  16714. }
  16715. if (this.infiniteDistance) {
  16716. return false;
  16717. }
  16718. if (!this._cache.position.equals(this.position))
  16719. return false;
  16720. if (this.rotationQuaternion) {
  16721. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16722. return false;
  16723. }
  16724. if (!this._cache.rotation.equals(this.rotation))
  16725. return false;
  16726. if (!this._cache.scaling.equals(this.scaling))
  16727. return false;
  16728. return true;
  16729. };
  16730. TransformNode.prototype._initCache = function () {
  16731. _super.prototype._initCache.call(this);
  16732. this._cache.localMatrixUpdated = false;
  16733. this._cache.position = BABYLON.Vector3.Zero();
  16734. this._cache.scaling = BABYLON.Vector3.Zero();
  16735. this._cache.rotation = BABYLON.Vector3.Zero();
  16736. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16737. this._cache.billboardMode = -1;
  16738. };
  16739. TransformNode.prototype.markAsDirty = function (property) {
  16740. if (property === "rotation") {
  16741. this.rotationQuaternion = null;
  16742. }
  16743. this._currentRenderId = Number.MAX_VALUE;
  16744. this._isDirty = true;
  16745. return this;
  16746. };
  16747. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16748. /**
  16749. * Returns the current mesh absolute position.
  16750. * Retuns a Vector3.
  16751. */
  16752. get: function () {
  16753. return this._absolutePosition;
  16754. },
  16755. enumerable: true,
  16756. configurable: true
  16757. });
  16758. /**
  16759. * Sets a new matrix to apply before all other transformation
  16760. * @param matrix defines the transform matrix
  16761. * @returns the current TransformNode
  16762. */
  16763. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16764. return this.setPivotMatrix(matrix, false);
  16765. };
  16766. /**
  16767. * Sets a new pivot matrix to the current node
  16768. * @param matrix defines the new pivot matrix to use
  16769. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16770. * @returns the current TransformNode
  16771. */
  16772. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16773. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16774. this._pivotMatrix = matrix.clone();
  16775. this._cache.pivotMatrixUpdated = true;
  16776. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16777. if (this._postMultiplyPivotMatrix) {
  16778. if (!this._pivotMatrixInverse) {
  16779. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16780. }
  16781. else {
  16782. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16783. }
  16784. }
  16785. return this;
  16786. };
  16787. /**
  16788. * Returns the mesh pivot matrix.
  16789. * Default : Identity.
  16790. * A Matrix is returned.
  16791. */
  16792. TransformNode.prototype.getPivotMatrix = function () {
  16793. return this._pivotMatrix;
  16794. };
  16795. /**
  16796. * Prevents the World matrix to be computed any longer.
  16797. * Returns the TransformNode.
  16798. */
  16799. TransformNode.prototype.freezeWorldMatrix = function () {
  16800. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16801. this.computeWorldMatrix(true);
  16802. this._isWorldMatrixFrozen = true;
  16803. return this;
  16804. };
  16805. /**
  16806. * Allows back the World matrix computation.
  16807. * Returns the TransformNode.
  16808. */
  16809. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16810. this._isWorldMatrixFrozen = false;
  16811. this.computeWorldMatrix(true);
  16812. return this;
  16813. };
  16814. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16815. /**
  16816. * True if the World matrix has been frozen.
  16817. * Returns a boolean.
  16818. */
  16819. get: function () {
  16820. return this._isWorldMatrixFrozen;
  16821. },
  16822. enumerable: true,
  16823. configurable: true
  16824. });
  16825. /**
  16826. * Retuns the mesh absolute position in the World.
  16827. * Returns a Vector3.
  16828. */
  16829. TransformNode.prototype.getAbsolutePosition = function () {
  16830. this.computeWorldMatrix();
  16831. return this._absolutePosition;
  16832. };
  16833. /**
  16834. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16835. * Returns the TransformNode.
  16836. */
  16837. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16838. if (!absolutePosition) {
  16839. return this;
  16840. }
  16841. var absolutePositionX;
  16842. var absolutePositionY;
  16843. var absolutePositionZ;
  16844. if (absolutePosition.x === undefined) {
  16845. if (arguments.length < 3) {
  16846. return this;
  16847. }
  16848. absolutePositionX = arguments[0];
  16849. absolutePositionY = arguments[1];
  16850. absolutePositionZ = arguments[2];
  16851. }
  16852. else {
  16853. absolutePositionX = absolutePosition.x;
  16854. absolutePositionY = absolutePosition.y;
  16855. absolutePositionZ = absolutePosition.z;
  16856. }
  16857. if (this.parent) {
  16858. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16859. invertParentWorldMatrix.invert();
  16860. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16861. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16862. }
  16863. else {
  16864. this.position.x = absolutePositionX;
  16865. this.position.y = absolutePositionY;
  16866. this.position.z = absolutePositionZ;
  16867. }
  16868. return this;
  16869. };
  16870. /**
  16871. * Sets the mesh position in its local space.
  16872. * Returns the TransformNode.
  16873. */
  16874. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16875. this.computeWorldMatrix();
  16876. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16877. return this;
  16878. };
  16879. /**
  16880. * Returns the mesh position in the local space from the current World matrix values.
  16881. * Returns a new Vector3.
  16882. */
  16883. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16884. this.computeWorldMatrix();
  16885. var invLocalWorldMatrix = this._localWorld.clone();
  16886. invLocalWorldMatrix.invert();
  16887. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16888. };
  16889. /**
  16890. * Translates the mesh along the passed Vector3 in its local space.
  16891. * Returns the TransformNode.
  16892. */
  16893. TransformNode.prototype.locallyTranslate = function (vector3) {
  16894. this.computeWorldMatrix(true);
  16895. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16896. return this;
  16897. };
  16898. /**
  16899. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16900. * @param targetPoint the position (must be in same space as current mesh) to look at
  16901. * @param yawCor optional yaw (y-axis) correction in radians
  16902. * @param pitchCor optional pitch (x-axis) correction in radians
  16903. * @param rollCor optional roll (z-axis) correction in radians
  16904. * @param space the choosen space of the target
  16905. * @returns the TransformNode.
  16906. */
  16907. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16908. if (yawCor === void 0) { yawCor = 0; }
  16909. if (pitchCor === void 0) { pitchCor = 0; }
  16910. if (rollCor === void 0) { rollCor = 0; }
  16911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16912. var dv = TransformNode._lookAtVectorCache;
  16913. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16914. targetPoint.subtractToRef(pos, dv);
  16915. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16916. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16917. var pitch = Math.atan2(dv.y, len);
  16918. if (this.rotationQuaternion) {
  16919. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16920. }
  16921. else {
  16922. this.rotation.x = pitch + pitchCor;
  16923. this.rotation.y = yaw + yawCor;
  16924. this.rotation.z = rollCor;
  16925. }
  16926. return this;
  16927. };
  16928. /**
  16929. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16930. * This Vector3 is expressed in the World space.
  16931. */
  16932. TransformNode.prototype.getDirection = function (localAxis) {
  16933. var result = BABYLON.Vector3.Zero();
  16934. this.getDirectionToRef(localAxis, result);
  16935. return result;
  16936. };
  16937. /**
  16938. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16939. * localAxis is expressed in the mesh local space.
  16940. * result is computed in the Wordl space from the mesh World matrix.
  16941. * Returns the TransformNode.
  16942. */
  16943. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16944. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16945. return this;
  16946. };
  16947. /**
  16948. * Sets a new pivot point to the current node
  16949. * @param point defines the new pivot point to use
  16950. * @param space defines if the point is in world or local space (local by default)
  16951. * @returns the current TransformNode
  16952. */
  16953. TransformNode.prototype.setPivotPoint = function (point, space) {
  16954. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16955. if (this.getScene().getRenderId() == 0) {
  16956. this.computeWorldMatrix(true);
  16957. }
  16958. var wm = this.getWorldMatrix();
  16959. if (space == BABYLON.Space.WORLD) {
  16960. var tmat = BABYLON.Tmp.Matrix[0];
  16961. wm.invertToRef(tmat);
  16962. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16963. }
  16964. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16965. };
  16966. /**
  16967. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16968. */
  16969. TransformNode.prototype.getPivotPoint = function () {
  16970. var point = BABYLON.Vector3.Zero();
  16971. this.getPivotPointToRef(point);
  16972. return point;
  16973. };
  16974. /**
  16975. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16976. * Returns the TransformNode.
  16977. */
  16978. TransformNode.prototype.getPivotPointToRef = function (result) {
  16979. result.x = -this._pivotMatrix.m[12];
  16980. result.y = -this._pivotMatrix.m[13];
  16981. result.z = -this._pivotMatrix.m[14];
  16982. return this;
  16983. };
  16984. /**
  16985. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16986. */
  16987. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16988. var point = BABYLON.Vector3.Zero();
  16989. this.getAbsolutePivotPointToRef(point);
  16990. return point;
  16991. };
  16992. /**
  16993. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16994. * Returns the TransformNode.
  16995. */
  16996. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16997. result.x = this._pivotMatrix.m[12];
  16998. result.y = this._pivotMatrix.m[13];
  16999. result.z = this._pivotMatrix.m[14];
  17000. this.getPivotPointToRef(result);
  17001. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17002. return this;
  17003. };
  17004. /**
  17005. * Defines the passed node as the parent of the current node.
  17006. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17007. * Returns the TransformNode.
  17008. */
  17009. TransformNode.prototype.setParent = function (node) {
  17010. if (node === null) {
  17011. var rotation = BABYLON.Tmp.Quaternion[0];
  17012. var position = BABYLON.Tmp.Vector3[0];
  17013. var scale = BABYLON.Tmp.Vector3[1];
  17014. if (this.parent && this.parent.computeWorldMatrix) {
  17015. this.parent.computeWorldMatrix(true);
  17016. }
  17017. this.computeWorldMatrix(true);
  17018. this.getWorldMatrix().decompose(scale, rotation, position);
  17019. if (this.rotationQuaternion) {
  17020. this.rotationQuaternion.copyFrom(rotation);
  17021. }
  17022. else {
  17023. rotation.toEulerAnglesToRef(this.rotation);
  17024. }
  17025. this.scaling.x = scale.x;
  17026. this.scaling.y = scale.y;
  17027. this.scaling.z = scale.z;
  17028. this.position.x = position.x;
  17029. this.position.y = position.y;
  17030. this.position.z = position.z;
  17031. }
  17032. else {
  17033. var rotation = BABYLON.Tmp.Quaternion[0];
  17034. var position = BABYLON.Tmp.Vector3[0];
  17035. var scale = BABYLON.Tmp.Vector3[1];
  17036. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17037. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17038. this.computeWorldMatrix(true);
  17039. node.computeWorldMatrix(true);
  17040. node.getWorldMatrix().invertToRef(invParentMatrix);
  17041. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17042. diffMatrix.decompose(scale, rotation, position);
  17043. if (this.rotationQuaternion) {
  17044. this.rotationQuaternion.copyFrom(rotation);
  17045. }
  17046. else {
  17047. rotation.toEulerAnglesToRef(this.rotation);
  17048. }
  17049. this.position.x = position.x;
  17050. this.position.y = position.y;
  17051. this.position.z = position.z;
  17052. this.scaling.x = scale.x;
  17053. this.scaling.y = scale.y;
  17054. this.scaling.z = scale.z;
  17055. }
  17056. this.parent = node;
  17057. return this;
  17058. };
  17059. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17060. get: function () {
  17061. return this._nonUniformScaling;
  17062. },
  17063. enumerable: true,
  17064. configurable: true
  17065. });
  17066. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17067. if (this._nonUniformScaling === value) {
  17068. return false;
  17069. }
  17070. this._nonUniformScaling = true;
  17071. return true;
  17072. };
  17073. /**
  17074. * Attach the current TransformNode to another TransformNode associated with a bone
  17075. * @param bone Bone affecting the TransformNode
  17076. * @param affectedTransformNode TransformNode associated with the bone
  17077. */
  17078. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17079. this._transformToBoneReferal = affectedTransformNode;
  17080. this.parent = bone;
  17081. if (bone.getWorldMatrix().determinant() < 0) {
  17082. this.scalingDeterminant *= -1;
  17083. }
  17084. return this;
  17085. };
  17086. TransformNode.prototype.detachFromBone = function () {
  17087. if (!this.parent) {
  17088. return this;
  17089. }
  17090. if (this.parent.getWorldMatrix().determinant() < 0) {
  17091. this.scalingDeterminant *= -1;
  17092. }
  17093. this._transformToBoneReferal = null;
  17094. this.parent = null;
  17095. return this;
  17096. };
  17097. /**
  17098. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17099. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17100. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17101. * The passed axis is also normalized.
  17102. * Returns the TransformNode.
  17103. */
  17104. TransformNode.prototype.rotate = function (axis, amount, space) {
  17105. axis.normalize();
  17106. if (!this.rotationQuaternion) {
  17107. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17108. this.rotation = BABYLON.Vector3.Zero();
  17109. }
  17110. var rotationQuaternion;
  17111. if (!space || space === BABYLON.Space.LOCAL) {
  17112. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17113. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17114. }
  17115. else {
  17116. if (this.parent) {
  17117. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17118. invertParentWorldMatrix.invert();
  17119. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17120. }
  17121. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17122. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17123. }
  17124. return this;
  17125. };
  17126. /**
  17127. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17128. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17129. * The passed axis is also normalized.
  17130. * Returns the TransformNode.
  17131. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17132. */
  17133. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17134. axis.normalize();
  17135. if (!this.rotationQuaternion) {
  17136. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17137. this.rotation.copyFromFloats(0, 0, 0);
  17138. }
  17139. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17140. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17141. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17142. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17143. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17144. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17145. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17146. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17147. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17148. return this;
  17149. };
  17150. /**
  17151. * Translates the mesh along the axis vector for the passed distance in the given space.
  17152. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17153. * Returns the TransformNode.
  17154. */
  17155. TransformNode.prototype.translate = function (axis, distance, space) {
  17156. var displacementVector = axis.scale(distance);
  17157. if (!space || space === BABYLON.Space.LOCAL) {
  17158. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17159. this.setPositionWithLocalVector(tempV3);
  17160. }
  17161. else {
  17162. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17163. }
  17164. return this;
  17165. };
  17166. /**
  17167. * Adds a rotation step to the mesh current rotation.
  17168. * x, y, z are Euler angles expressed in radians.
  17169. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17170. * This means this rotation is made in the mesh local space only.
  17171. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17172. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17173. * ```javascript
  17174. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17175. * ```
  17176. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17177. * 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.
  17178. * Returns the TransformNode.
  17179. */
  17180. TransformNode.prototype.addRotation = function (x, y, z) {
  17181. var rotationQuaternion;
  17182. if (this.rotationQuaternion) {
  17183. rotationQuaternion = this.rotationQuaternion;
  17184. }
  17185. else {
  17186. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17187. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17188. }
  17189. var accumulation = BABYLON.Tmp.Quaternion[0];
  17190. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17191. rotationQuaternion.multiplyInPlace(accumulation);
  17192. if (!this.rotationQuaternion) {
  17193. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17194. }
  17195. return this;
  17196. };
  17197. /**
  17198. * Computes the mesh World matrix and returns it.
  17199. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17200. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17201. * If the parameter `force`is set to `true`, the actual computation is done.
  17202. * Returns the mesh World Matrix.
  17203. */
  17204. TransformNode.prototype.computeWorldMatrix = function (force) {
  17205. if (this._isWorldMatrixFrozen) {
  17206. return this._worldMatrix;
  17207. }
  17208. if (!force && this.isSynchronized(true)) {
  17209. this._currentRenderId = this.getScene().getRenderId();
  17210. return this._worldMatrix;
  17211. }
  17212. this._cache.position.copyFrom(this.position);
  17213. this._cache.scaling.copyFrom(this.scaling);
  17214. this._cache.pivotMatrixUpdated = false;
  17215. this._cache.billboardMode = this.billboardMode;
  17216. this._currentRenderId = this.getScene().getRenderId();
  17217. this._childRenderId = this.getScene().getRenderId();
  17218. this._isDirty = false;
  17219. // Scaling
  17220. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17221. // Rotation
  17222. //rotate, if quaternion is set and rotation was used
  17223. if (this.rotationQuaternion) {
  17224. var len = this.rotation.length();
  17225. if (len) {
  17226. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17227. this.rotation.copyFromFloats(0, 0, 0);
  17228. }
  17229. }
  17230. if (this.rotationQuaternion) {
  17231. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17232. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17233. }
  17234. else {
  17235. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17236. this._cache.rotation.copyFrom(this.rotation);
  17237. }
  17238. // Translation
  17239. var camera = this.getScene().activeCamera;
  17240. if (this.infiniteDistance && !this.parent && camera) {
  17241. var cameraWorldMatrix = camera.getWorldMatrix();
  17242. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17243. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17244. }
  17245. else {
  17246. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17247. }
  17248. // Composing transformations
  17249. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17250. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17251. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17252. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17253. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17254. // Need to decompose each rotation here
  17255. var currentPosition = BABYLON.Tmp.Vector3[3];
  17256. if (this.parent && this.parent.getWorldMatrix) {
  17257. if (this._transformToBoneReferal) {
  17258. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17259. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17260. }
  17261. else {
  17262. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17263. }
  17264. }
  17265. else {
  17266. currentPosition.copyFrom(this.position);
  17267. }
  17268. currentPosition.subtractInPlace(camera.globalPosition);
  17269. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17270. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17271. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17272. }
  17273. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17274. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17275. }
  17276. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17277. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17278. }
  17279. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17280. }
  17281. else {
  17282. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17283. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17284. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17285. }
  17286. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17287. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17288. }
  17289. // Local world
  17290. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17291. // Parent
  17292. if (this.parent && this.parent.getWorldMatrix) {
  17293. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17294. if (this._transformToBoneReferal) {
  17295. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17296. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17297. }
  17298. else {
  17299. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17300. }
  17301. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17302. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17303. this._worldMatrix.copyFrom(this._localWorld);
  17304. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17305. }
  17306. else {
  17307. if (this._transformToBoneReferal) {
  17308. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17309. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17310. }
  17311. else {
  17312. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17313. }
  17314. }
  17315. this._markSyncedWithParent();
  17316. }
  17317. else {
  17318. this._worldMatrix.copyFrom(this._localWorld);
  17319. }
  17320. // Post multiply inverse of pivotMatrix
  17321. if (this._postMultiplyPivotMatrix) {
  17322. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17323. }
  17324. // Normal matrix
  17325. if (this.scaling.isNonUniform) {
  17326. this._updateNonUniformScalingState(true);
  17327. }
  17328. else if (this.parent && this.parent._nonUniformScaling) {
  17329. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17330. }
  17331. else {
  17332. this._updateNonUniformScalingState(false);
  17333. }
  17334. this._afterComputeWorldMatrix();
  17335. // Absolute position
  17336. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17337. // Callbacks
  17338. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17339. if (!this._poseMatrix) {
  17340. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17341. }
  17342. // Cache the determinant
  17343. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17344. return this._worldMatrix;
  17345. };
  17346. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17347. };
  17348. /**
  17349. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17350. * @param func: callback function to add
  17351. *
  17352. * Returns the TransformNode.
  17353. */
  17354. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17355. this.onAfterWorldMatrixUpdateObservable.add(func);
  17356. return this;
  17357. };
  17358. /**
  17359. * Removes a registered callback function.
  17360. * Returns the TransformNode.
  17361. */
  17362. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17363. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17364. return this;
  17365. };
  17366. /**
  17367. * Clone the current transform node
  17368. * Returns the new transform node
  17369. * @param name Name of the new clone
  17370. * @param newParent New parent for the clone
  17371. * @param doNotCloneChildren Do not clone children hierarchy
  17372. */
  17373. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17374. var _this = this;
  17375. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17376. result.name = name;
  17377. result.id = name;
  17378. if (newParent) {
  17379. result.parent = newParent;
  17380. }
  17381. if (!doNotCloneChildren) {
  17382. // Children
  17383. var directDescendants = this.getDescendants(true);
  17384. for (var index = 0; index < directDescendants.length; index++) {
  17385. var child = directDescendants[index];
  17386. if (child.clone) {
  17387. child.clone(name + "." + child.name, result);
  17388. }
  17389. }
  17390. }
  17391. return result;
  17392. };
  17393. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17394. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17395. serializationObject.type = this.getClassName();
  17396. // Parent
  17397. if (this.parent) {
  17398. serializationObject.parentId = this.parent.id;
  17399. }
  17400. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17401. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17402. }
  17403. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17404. serializationObject.isEnabled = this.isEnabled();
  17405. // Parent
  17406. if (this.parent) {
  17407. serializationObject.parentId = this.parent.id;
  17408. }
  17409. return serializationObject;
  17410. };
  17411. // Statics
  17412. /**
  17413. * Returns a new TransformNode object parsed from the source provided.
  17414. * The parameter `parsedMesh` is the source.
  17415. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17416. */
  17417. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17418. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17419. if (BABYLON.Tags) {
  17420. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17421. }
  17422. if (parsedTransformNode.localMatrix) {
  17423. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17424. }
  17425. else if (parsedTransformNode.pivotMatrix) {
  17426. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17427. }
  17428. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17429. // Parent
  17430. if (parsedTransformNode.parentId) {
  17431. transformNode._waitingParentId = parsedTransformNode.parentId;
  17432. }
  17433. return transformNode;
  17434. };
  17435. /**
  17436. * Releases resources associated with this transform node.
  17437. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17438. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17439. */
  17440. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17441. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17442. // Animations
  17443. this.getScene().stopAnimation(this);
  17444. // Remove from scene
  17445. this.getScene().removeTransformNode(this);
  17446. this.onAfterWorldMatrixUpdateObservable.clear();
  17447. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17448. };
  17449. // Statics
  17450. TransformNode.BILLBOARDMODE_NONE = 0;
  17451. TransformNode.BILLBOARDMODE_X = 1;
  17452. TransformNode.BILLBOARDMODE_Y = 2;
  17453. TransformNode.BILLBOARDMODE_Z = 4;
  17454. TransformNode.BILLBOARDMODE_ALL = 7;
  17455. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17456. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17457. __decorate([
  17458. BABYLON.serializeAsVector3()
  17459. ], TransformNode.prototype, "_rotation", void 0);
  17460. __decorate([
  17461. BABYLON.serializeAsQuaternion()
  17462. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17463. __decorate([
  17464. BABYLON.serializeAsVector3()
  17465. ], TransformNode.prototype, "_scaling", void 0);
  17466. __decorate([
  17467. BABYLON.serialize()
  17468. ], TransformNode.prototype, "billboardMode", void 0);
  17469. __decorate([
  17470. BABYLON.serialize()
  17471. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17472. __decorate([
  17473. BABYLON.serialize()
  17474. ], TransformNode.prototype, "infiniteDistance", void 0);
  17475. __decorate([
  17476. BABYLON.serializeAsVector3()
  17477. ], TransformNode.prototype, "position", void 0);
  17478. return TransformNode;
  17479. }(BABYLON.Node));
  17480. BABYLON.TransformNode = TransformNode;
  17481. })(BABYLON || (BABYLON = {}));
  17482. //# sourceMappingURL=babylon.transformNode.js.map
  17483. "use strict";
  17484. var BABYLON;
  17485. (function (BABYLON) {
  17486. var AbstractMesh = /** @class */ (function (_super) {
  17487. __extends(AbstractMesh, _super);
  17488. // Constructor
  17489. function AbstractMesh(name, scene) {
  17490. if (scene === void 0) { scene = null; }
  17491. var _this = _super.call(this, name, scene, false) || this;
  17492. _this._facetNb = 0; // facet number
  17493. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17494. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17495. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17496. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17497. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17498. _this._subDiv = {
  17499. max: 1,
  17500. X: 1,
  17501. Y: 1,
  17502. Z: 1
  17503. };
  17504. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17505. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17506. // Events
  17507. /**
  17508. * An event triggered when this mesh collides with another one
  17509. */
  17510. _this.onCollideObservable = new BABYLON.Observable();
  17511. /**
  17512. * An event triggered when the collision's position changes
  17513. */
  17514. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17515. /**
  17516. * An event triggered when material is changed
  17517. */
  17518. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17519. // Properties
  17520. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17521. /**
  17522. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17523. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17524. * or
  17525. * 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.
  17526. * for more info check WebGl documentations
  17527. */
  17528. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17529. /**
  17530. * 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:
  17531. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17532. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17533. * 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.
  17534. */
  17535. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17536. /**
  17537. * 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.
  17538. * The default value is -1 which means don't break the query and wait till the result.
  17539. */
  17540. _this.occlusionRetryCount = -1;
  17541. _this._occlusionInternalRetryCounter = 0;
  17542. _this._isOccluded = false;
  17543. _this._isOcclusionQueryInProgress = false;
  17544. _this._visibility = 1.0;
  17545. _this.alphaIndex = Number.MAX_VALUE;
  17546. _this.isVisible = true;
  17547. _this.isPickable = true;
  17548. _this.showBoundingBox = false;
  17549. _this.showSubMeshesBoundingBox = false;
  17550. _this.isBlocker = false;
  17551. _this.enablePointerMoveEvents = false;
  17552. _this.renderingGroupId = 0;
  17553. _this._receiveShadows = false;
  17554. _this.renderOutline = false;
  17555. _this.outlineColor = BABYLON.Color3.Red();
  17556. _this.outlineWidth = 0.02;
  17557. _this.renderOverlay = false;
  17558. _this.overlayColor = BABYLON.Color3.Red();
  17559. _this.overlayAlpha = 0.5;
  17560. _this._hasVertexAlpha = false;
  17561. _this._useVertexColors = true;
  17562. _this._computeBonesUsingShaders = true;
  17563. _this._numBoneInfluencers = 4;
  17564. _this._applyFog = true;
  17565. _this.useOctreeForRenderingSelection = true;
  17566. _this.useOctreeForPicking = true;
  17567. _this.useOctreeForCollisions = true;
  17568. _this._layerMask = 0x0FFFFFFF;
  17569. /**
  17570. * True if the mesh must be rendered in any case.
  17571. */
  17572. _this.alwaysSelectAsActiveMesh = false;
  17573. /**
  17574. * This scene's action manager
  17575. */
  17576. _this.actionManager = null;
  17577. // Physics
  17578. _this.physicsImpostor = null;
  17579. // Collisions
  17580. _this._checkCollisions = false;
  17581. _this._collisionMask = -1;
  17582. _this._collisionGroup = -1;
  17583. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17584. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17585. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17586. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17587. // Edges
  17588. _this.edgesWidth = 1;
  17589. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17590. // Cache
  17591. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17592. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17593. _this._renderId = 0;
  17594. _this._intersectionsInProgress = new Array();
  17595. _this._unIndexed = false;
  17596. _this._lightSources = new Array();
  17597. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17598. if (collidedMesh === void 0) { collidedMesh = null; }
  17599. //TODO move this to the collision coordinator!
  17600. if (_this.getScene().workerCollisions)
  17601. newPosition.multiplyInPlace(_this._collider._radius);
  17602. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17603. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17604. _this.position.addInPlace(_this._diffPositionForCollisions);
  17605. }
  17606. if (collidedMesh) {
  17607. _this.onCollideObservable.notifyObservers(collidedMesh);
  17608. }
  17609. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17610. };
  17611. _this.getScene().addMesh(_this);
  17612. _this._resyncLightSources();
  17613. return _this;
  17614. }
  17615. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17616. get: function () {
  17617. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17618. },
  17619. enumerable: true,
  17620. configurable: true
  17621. });
  17622. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17623. get: function () {
  17624. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17625. },
  17626. enumerable: true,
  17627. configurable: true
  17628. });
  17629. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17630. get: function () {
  17631. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17632. },
  17633. enumerable: true,
  17634. configurable: true
  17635. });
  17636. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17637. get: function () {
  17638. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17644. get: function () {
  17645. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17646. },
  17647. enumerable: true,
  17648. configurable: true
  17649. });
  17650. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17651. /**
  17652. * Read-only : the number of facets in the mesh
  17653. */
  17654. get: function () {
  17655. return this._facetNb;
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17661. /**
  17662. * The number (integer) of subdivisions per axis in the partioning space
  17663. */
  17664. get: function () {
  17665. return this._partitioningSubdivisions;
  17666. },
  17667. set: function (nb) {
  17668. this._partitioningSubdivisions = nb;
  17669. },
  17670. enumerable: true,
  17671. configurable: true
  17672. });
  17673. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17674. /**
  17675. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17676. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17677. */
  17678. get: function () {
  17679. return this._partitioningBBoxRatio;
  17680. },
  17681. set: function (ratio) {
  17682. this._partitioningBBoxRatio = ratio;
  17683. },
  17684. enumerable: true,
  17685. configurable: true
  17686. });
  17687. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17688. /**
  17689. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17690. * Works only for updatable meshes.
  17691. * Doesn't work with multi-materials.
  17692. */
  17693. get: function () {
  17694. return this._facetDepthSort;
  17695. },
  17696. set: function (sort) {
  17697. this._facetDepthSort = sort;
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17703. /**
  17704. * The location (Vector3) where the facet depth sort must be computed from.
  17705. * By default, the active camera position.
  17706. * Used only when facet depth sort is enabled.
  17707. */
  17708. get: function () {
  17709. return this._facetDepthSortFrom;
  17710. },
  17711. set: function (location) {
  17712. this._facetDepthSortFrom = location;
  17713. },
  17714. enumerable: true,
  17715. configurable: true
  17716. });
  17717. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17718. /**
  17719. * Read-only boolean : is the feature facetData enabled ?
  17720. */
  17721. get: function () {
  17722. return this._facetDataEnabled;
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17728. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17729. return false;
  17730. }
  17731. this._markSubMeshesAsMiscDirty();
  17732. return true;
  17733. };
  17734. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17735. set: function (callback) {
  17736. if (this._onCollideObserver) {
  17737. this.onCollideObservable.remove(this._onCollideObserver);
  17738. }
  17739. this._onCollideObserver = this.onCollideObservable.add(callback);
  17740. },
  17741. enumerable: true,
  17742. configurable: true
  17743. });
  17744. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17745. set: function (callback) {
  17746. if (this._onCollisionPositionChangeObserver) {
  17747. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17748. }
  17749. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17755. /**
  17756. * 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.
  17757. */
  17758. get: function () {
  17759. return this._isOccluded;
  17760. },
  17761. set: function (value) {
  17762. this._isOccluded = value;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17768. /**
  17769. * Flag to check the progress status of the query
  17770. */
  17771. get: function () {
  17772. return this._isOcclusionQueryInProgress;
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17778. /**
  17779. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17780. */
  17781. get: function () {
  17782. return this._visibility;
  17783. },
  17784. /**
  17785. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17786. */
  17787. set: function (value) {
  17788. if (this._visibility === value) {
  17789. return;
  17790. }
  17791. this._visibility = value;
  17792. this._markSubMeshesAsMiscDirty();
  17793. },
  17794. enumerable: true,
  17795. configurable: true
  17796. });
  17797. Object.defineProperty(AbstractMesh.prototype, "material", {
  17798. get: function () {
  17799. return this._material;
  17800. },
  17801. set: function (value) {
  17802. if (this._material === value) {
  17803. return;
  17804. }
  17805. this._material = value;
  17806. if (this.onMaterialChangedObservable.hasObservers) {
  17807. this.onMaterialChangedObservable.notifyObservers(this);
  17808. }
  17809. if (!this.subMeshes) {
  17810. return;
  17811. }
  17812. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17813. var subMesh = _a[_i];
  17814. subMesh.setEffect(null);
  17815. }
  17816. },
  17817. enumerable: true,
  17818. configurable: true
  17819. });
  17820. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17821. get: function () {
  17822. return this._receiveShadows;
  17823. },
  17824. set: function (value) {
  17825. if (this._receiveShadows === value) {
  17826. return;
  17827. }
  17828. this._receiveShadows = value;
  17829. this._markSubMeshesAsLightDirty();
  17830. },
  17831. enumerable: true,
  17832. configurable: true
  17833. });
  17834. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17835. get: function () {
  17836. return this._hasVertexAlpha;
  17837. },
  17838. set: function (value) {
  17839. if (this._hasVertexAlpha === value) {
  17840. return;
  17841. }
  17842. this._hasVertexAlpha = value;
  17843. this._markSubMeshesAsAttributesDirty();
  17844. this._markSubMeshesAsMiscDirty();
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17850. get: function () {
  17851. return this._useVertexColors;
  17852. },
  17853. set: function (value) {
  17854. if (this._useVertexColors === value) {
  17855. return;
  17856. }
  17857. this._useVertexColors = value;
  17858. this._markSubMeshesAsAttributesDirty();
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17864. get: function () {
  17865. return this._computeBonesUsingShaders;
  17866. },
  17867. set: function (value) {
  17868. if (this._computeBonesUsingShaders === value) {
  17869. return;
  17870. }
  17871. this._computeBonesUsingShaders = value;
  17872. this._markSubMeshesAsAttributesDirty();
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17878. get: function () {
  17879. return this._numBoneInfluencers;
  17880. },
  17881. set: function (value) {
  17882. if (this._numBoneInfluencers === value) {
  17883. return;
  17884. }
  17885. this._numBoneInfluencers = value;
  17886. this._markSubMeshesAsAttributesDirty();
  17887. },
  17888. enumerable: true,
  17889. configurable: true
  17890. });
  17891. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17892. get: function () {
  17893. return this._applyFog;
  17894. },
  17895. set: function (value) {
  17896. if (this._applyFog === value) {
  17897. return;
  17898. }
  17899. this._applyFog = value;
  17900. this._markSubMeshesAsMiscDirty();
  17901. },
  17902. enumerable: true,
  17903. configurable: true
  17904. });
  17905. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17906. get: function () {
  17907. return this._layerMask;
  17908. },
  17909. set: function (value) {
  17910. if (value === this._layerMask) {
  17911. return;
  17912. }
  17913. this._layerMask = value;
  17914. this._resyncLightSources();
  17915. },
  17916. enumerable: true,
  17917. configurable: true
  17918. });
  17919. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17920. get: function () {
  17921. return this._collisionMask;
  17922. },
  17923. set: function (mask) {
  17924. this._collisionMask = !isNaN(mask) ? mask : -1;
  17925. },
  17926. enumerable: true,
  17927. configurable: true
  17928. });
  17929. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17930. get: function () {
  17931. return this._collisionGroup;
  17932. },
  17933. set: function (mask) {
  17934. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17935. },
  17936. enumerable: true,
  17937. configurable: true
  17938. });
  17939. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17940. get: function () {
  17941. return null;
  17942. },
  17943. enumerable: true,
  17944. configurable: true
  17945. });
  17946. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17947. get: function () {
  17948. return this._skeleton;
  17949. },
  17950. set: function (value) {
  17951. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17952. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17953. }
  17954. if (value && value.needInitialSkinMatrix) {
  17955. value._registerMeshWithPoseMatrix(this);
  17956. }
  17957. this._skeleton = value;
  17958. if (!this._skeleton) {
  17959. this._bonesTransformMatrices = null;
  17960. }
  17961. this._markSubMeshesAsAttributesDirty();
  17962. },
  17963. enumerable: true,
  17964. configurable: true
  17965. });
  17966. /**
  17967. * Returns the string "AbstractMesh"
  17968. */
  17969. AbstractMesh.prototype.getClassName = function () {
  17970. return "AbstractMesh";
  17971. };
  17972. /**
  17973. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17974. */
  17975. AbstractMesh.prototype.toString = function (fullDetails) {
  17976. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17977. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17978. if (this._skeleton) {
  17979. ret += ", skeleton: " + this._skeleton.name;
  17980. }
  17981. if (fullDetails) {
  17982. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17983. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17984. }
  17985. return ret;
  17986. };
  17987. AbstractMesh.prototype._rebuild = function () {
  17988. if (this._occlusionQuery) {
  17989. this._occlusionQuery = null;
  17990. }
  17991. if (this._edgesRenderer) {
  17992. this._edgesRenderer._rebuild();
  17993. }
  17994. if (!this.subMeshes) {
  17995. return;
  17996. }
  17997. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17998. var subMesh = _a[_i];
  17999. subMesh._rebuild();
  18000. }
  18001. };
  18002. AbstractMesh.prototype._resyncLightSources = function () {
  18003. this._lightSources.length = 0;
  18004. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18005. var light = _a[_i];
  18006. if (!light.isEnabled()) {
  18007. continue;
  18008. }
  18009. if (light.canAffectMesh(this)) {
  18010. this._lightSources.push(light);
  18011. }
  18012. }
  18013. this._markSubMeshesAsLightDirty();
  18014. };
  18015. AbstractMesh.prototype._resyncLighSource = function (light) {
  18016. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18017. var index = this._lightSources.indexOf(light);
  18018. if (index === -1) {
  18019. if (!isIn) {
  18020. return;
  18021. }
  18022. this._lightSources.push(light);
  18023. }
  18024. else {
  18025. if (isIn) {
  18026. return;
  18027. }
  18028. this._lightSources.splice(index, 1);
  18029. }
  18030. this._markSubMeshesAsLightDirty();
  18031. };
  18032. AbstractMesh.prototype._removeLightSource = function (light) {
  18033. var index = this._lightSources.indexOf(light);
  18034. if (index === -1) {
  18035. return;
  18036. }
  18037. this._lightSources.splice(index, 1);
  18038. this._markSubMeshesAsLightDirty();
  18039. };
  18040. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18041. if (!this.subMeshes) {
  18042. return;
  18043. }
  18044. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18045. var subMesh = _a[_i];
  18046. if (subMesh._materialDefines) {
  18047. func(subMesh._materialDefines);
  18048. }
  18049. }
  18050. };
  18051. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18052. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18053. };
  18054. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18055. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18056. };
  18057. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18058. if (!this.subMeshes) {
  18059. return;
  18060. }
  18061. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18062. var subMesh = _a[_i];
  18063. var material = subMesh.getMaterial();
  18064. if (material) {
  18065. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18066. }
  18067. }
  18068. };
  18069. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18070. /**
  18071. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18072. * Default : (1.0, 1.0, 1.0)
  18073. */
  18074. get: function () {
  18075. return this._scaling;
  18076. },
  18077. /**
  18078. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18079. * Default : (1.0, 1.0, 1.0)
  18080. */
  18081. set: function (newScaling) {
  18082. this._scaling = newScaling;
  18083. if (this.physicsImpostor) {
  18084. this.physicsImpostor.forceUpdate();
  18085. }
  18086. },
  18087. enumerable: true,
  18088. configurable: true
  18089. });
  18090. // Methods
  18091. /**
  18092. * Disables the mesh edger rendering mode.
  18093. * Returns the AbstractMesh.
  18094. */
  18095. AbstractMesh.prototype.disableEdgesRendering = function () {
  18096. if (this._edgesRenderer) {
  18097. this._edgesRenderer.dispose();
  18098. this._edgesRenderer = null;
  18099. }
  18100. return this;
  18101. };
  18102. /**
  18103. * Enables the edge rendering mode on the mesh.
  18104. * This mode makes the mesh edges visible.
  18105. * Returns the AbstractMesh.
  18106. */
  18107. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18108. if (epsilon === void 0) { epsilon = 0.95; }
  18109. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18110. this.disableEdgesRendering();
  18111. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18112. return this;
  18113. };
  18114. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18115. /**
  18116. * Returns true if the mesh is blocked. Used by the class Mesh.
  18117. * Returns the boolean `false` by default.
  18118. */
  18119. get: function () {
  18120. return false;
  18121. },
  18122. enumerable: true,
  18123. configurable: true
  18124. });
  18125. /**
  18126. * Returns the mesh itself by default, used by the class Mesh.
  18127. * Returned type : AbstractMesh
  18128. */
  18129. AbstractMesh.prototype.getLOD = function (camera) {
  18130. return this;
  18131. };
  18132. /**
  18133. * Returns 0 by default, used by the class Mesh.
  18134. * Returns an integer.
  18135. */
  18136. AbstractMesh.prototype.getTotalVertices = function () {
  18137. return 0;
  18138. };
  18139. /**
  18140. * Returns null by default, used by the class Mesh.
  18141. * Returned type : integer array
  18142. */
  18143. AbstractMesh.prototype.getIndices = function () {
  18144. return null;
  18145. };
  18146. /**
  18147. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18148. * Returned type : float array or Float32Array
  18149. */
  18150. AbstractMesh.prototype.getVerticesData = function (kind) {
  18151. return null;
  18152. };
  18153. /**
  18154. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18155. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18156. * The `data` are either a numeric array either a Float32Array.
  18157. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18158. * 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).
  18159. * Note that a new underlying VertexBuffer object is created each call.
  18160. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18161. *
  18162. * Possible `kind` values :
  18163. * - BABYLON.VertexBuffer.PositionKind
  18164. * - BABYLON.VertexBuffer.UVKind
  18165. * - BABYLON.VertexBuffer.UV2Kind
  18166. * - BABYLON.VertexBuffer.UV3Kind
  18167. * - BABYLON.VertexBuffer.UV4Kind
  18168. * - BABYLON.VertexBuffer.UV5Kind
  18169. * - BABYLON.VertexBuffer.UV6Kind
  18170. * - BABYLON.VertexBuffer.ColorKind
  18171. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18172. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18173. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18174. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18175. *
  18176. * Returns the Mesh.
  18177. */
  18178. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18179. return this;
  18180. };
  18181. /**
  18182. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18183. * If the mesh has no geometry, it is simply returned as it is.
  18184. * The `data` are either a numeric array either a Float32Array.
  18185. * No new underlying VertexBuffer object is created.
  18186. * 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.
  18187. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18188. *
  18189. * Possible `kind` values :
  18190. * - BABYLON.VertexBuffer.PositionKind
  18191. * - BABYLON.VertexBuffer.UVKind
  18192. * - BABYLON.VertexBuffer.UV2Kind
  18193. * - BABYLON.VertexBuffer.UV3Kind
  18194. * - BABYLON.VertexBuffer.UV4Kind
  18195. * - BABYLON.VertexBuffer.UV5Kind
  18196. * - BABYLON.VertexBuffer.UV6Kind
  18197. * - BABYLON.VertexBuffer.ColorKind
  18198. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18199. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18200. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18201. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18202. *
  18203. * Returns the Mesh.
  18204. */
  18205. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18206. return this;
  18207. };
  18208. /**
  18209. * Sets the mesh indices.
  18210. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18211. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18212. * This method creates a new index buffer each call.
  18213. * Returns the Mesh.
  18214. */
  18215. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18216. return this;
  18217. };
  18218. /** Returns false by default, used by the class Mesh.
  18219. * Returns a boolean
  18220. */
  18221. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18222. return false;
  18223. };
  18224. /**
  18225. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18226. * Returns a BoundingInfo
  18227. */
  18228. AbstractMesh.prototype.getBoundingInfo = function () {
  18229. if (this._masterMesh) {
  18230. return this._masterMesh.getBoundingInfo();
  18231. }
  18232. if (!this._boundingInfo) {
  18233. // this._boundingInfo is being created here
  18234. this._updateBoundingInfo();
  18235. }
  18236. // cannot be null.
  18237. return this._boundingInfo;
  18238. };
  18239. /**
  18240. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18241. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18242. */
  18243. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18244. if (includeDescendants === void 0) { includeDescendants = true; }
  18245. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18246. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18247. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18248. if (maxDimension === 0) {
  18249. return this;
  18250. }
  18251. var scale = 1 / maxDimension;
  18252. this.scaling.scaleInPlace(scale);
  18253. return this;
  18254. };
  18255. /**
  18256. * Sets a mesh new object BoundingInfo.
  18257. * Returns the AbstractMesh.
  18258. */
  18259. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18260. this._boundingInfo = boundingInfo;
  18261. return this;
  18262. };
  18263. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18264. get: function () {
  18265. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18266. },
  18267. enumerable: true,
  18268. configurable: true
  18269. });
  18270. AbstractMesh.prototype._preActivate = function () {
  18271. };
  18272. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18273. };
  18274. AbstractMesh.prototype._activate = function (renderId) {
  18275. this._renderId = renderId;
  18276. };
  18277. /**
  18278. * Returns the latest update of the World matrix
  18279. * Returns a Matrix.
  18280. */
  18281. AbstractMesh.prototype.getWorldMatrix = function () {
  18282. if (this._masterMesh) {
  18283. return this._masterMesh.getWorldMatrix();
  18284. }
  18285. return _super.prototype.getWorldMatrix.call(this);
  18286. };
  18287. /**
  18288. * Returns the latest update of the World matrix determinant.
  18289. */
  18290. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18291. if (this._masterMesh) {
  18292. return this._masterMesh._getWorldMatrixDeterminant();
  18293. }
  18294. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18295. };
  18296. // ================================== Point of View Movement =================================
  18297. /**
  18298. * Perform relative position change from the point of view of behind the front of the mesh.
  18299. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18300. * Supports definition of mesh facing forward or backward.
  18301. * @param {number} amountRight
  18302. * @param {number} amountUp
  18303. * @param {number} amountForward
  18304. *
  18305. * Returns the AbstractMesh.
  18306. */
  18307. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18308. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18309. return this;
  18310. };
  18311. /**
  18312. * Calculate relative position change from the point of view of behind the front of the mesh.
  18313. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18314. * Supports definition of mesh facing forward or backward.
  18315. * @param {number} amountRight
  18316. * @param {number} amountUp
  18317. * @param {number} amountForward
  18318. *
  18319. * Returns a new Vector3.
  18320. */
  18321. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18322. var rotMatrix = new BABYLON.Matrix();
  18323. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18324. rotQuaternion.toRotationMatrix(rotMatrix);
  18325. var translationDelta = BABYLON.Vector3.Zero();
  18326. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18327. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18328. return translationDelta;
  18329. };
  18330. // ================================== Point of View Rotation =================================
  18331. /**
  18332. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18333. * Supports definition of mesh facing forward or backward.
  18334. * @param {number} flipBack
  18335. * @param {number} twirlClockwise
  18336. * @param {number} tiltRight
  18337. *
  18338. * Returns the AbstractMesh.
  18339. */
  18340. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18341. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18342. return this;
  18343. };
  18344. /**
  18345. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18346. * Supports definition of mesh facing forward or backward.
  18347. * @param {number} flipBack
  18348. * @param {number} twirlClockwise
  18349. * @param {number} tiltRight
  18350. *
  18351. * Returns a new Vector3.
  18352. */
  18353. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18354. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18355. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18356. };
  18357. /**
  18358. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18359. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18360. */
  18361. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18362. if (includeDescendants === void 0) { includeDescendants = true; }
  18363. this.computeWorldMatrix(true);
  18364. var min;
  18365. var max;
  18366. var boundingInfo = this.getBoundingInfo();
  18367. if (!this.subMeshes) {
  18368. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18369. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18370. }
  18371. else {
  18372. min = boundingInfo.boundingBox.minimumWorld;
  18373. max = boundingInfo.boundingBox.maximumWorld;
  18374. }
  18375. if (includeDescendants) {
  18376. var descendants = this.getDescendants(false);
  18377. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18378. var descendant = descendants_1[_i];
  18379. var childMesh = descendant;
  18380. childMesh.computeWorldMatrix(true);
  18381. //make sure we have the needed params to get mix and max
  18382. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18383. continue;
  18384. }
  18385. var childBoundingInfo = childMesh.getBoundingInfo();
  18386. var boundingBox = childBoundingInfo.boundingBox;
  18387. var minBox = boundingBox.minimumWorld;
  18388. var maxBox = boundingBox.maximumWorld;
  18389. BABYLON.Tools.CheckExtends(minBox, min, max);
  18390. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18391. }
  18392. }
  18393. return {
  18394. min: min,
  18395. max: max
  18396. };
  18397. };
  18398. /**
  18399. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18400. * Returns the AbstractMesh.
  18401. */
  18402. AbstractMesh.prototype._updateBoundingInfo = function () {
  18403. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18404. this._boundingInfo.update(this.worldMatrixFromCache);
  18405. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18406. return this;
  18407. };
  18408. /**
  18409. * Update a mesh's children BoundingInfo objects only.
  18410. * Returns the AbstractMesh.
  18411. */
  18412. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18413. if (!this.subMeshes) {
  18414. return this;
  18415. }
  18416. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18417. var subMesh = this.subMeshes[subIndex];
  18418. if (!subMesh.IsGlobal) {
  18419. subMesh.updateBoundingInfo(matrix);
  18420. }
  18421. }
  18422. return this;
  18423. };
  18424. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18425. // Bounding info
  18426. this._updateBoundingInfo();
  18427. };
  18428. /**
  18429. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18430. * A mesh is in the frustum if its bounding box intersects the frustum.
  18431. * Boolean returned.
  18432. */
  18433. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18434. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18435. };
  18436. /**
  18437. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18438. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18439. * Boolean returned.
  18440. */
  18441. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18442. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18443. ;
  18444. };
  18445. /**
  18446. * True if the mesh intersects another mesh or a SolidParticle object.
  18447. * 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)
  18448. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18449. * Returns a boolean.
  18450. */
  18451. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18452. if (precise === void 0) { precise = false; }
  18453. if (!this._boundingInfo || !mesh._boundingInfo) {
  18454. return false;
  18455. }
  18456. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18457. return true;
  18458. }
  18459. if (includeDescendants) {
  18460. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18461. var child = _a[_i];
  18462. if (child.intersectsMesh(mesh, precise, true)) {
  18463. return true;
  18464. }
  18465. }
  18466. }
  18467. return false;
  18468. };
  18469. /**
  18470. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18471. * Returns a boolean.
  18472. */
  18473. AbstractMesh.prototype.intersectsPoint = function (point) {
  18474. if (!this._boundingInfo) {
  18475. return false;
  18476. }
  18477. return this._boundingInfo.intersectsPoint(point);
  18478. };
  18479. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18480. return this.physicsImpostor;
  18481. };
  18482. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18483. if (camera === void 0) { camera = null; }
  18484. if (!camera) {
  18485. camera = this.getScene().activeCamera;
  18486. }
  18487. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18488. };
  18489. /**
  18490. * Returns the distance from the mesh to the active camera.
  18491. * Returns a float.
  18492. */
  18493. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18494. if (camera === void 0) { camera = null; }
  18495. if (!camera) {
  18496. camera = this.getScene().activeCamera;
  18497. }
  18498. return this.absolutePosition.subtract(camera.position).length();
  18499. };
  18500. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18501. if (!this.physicsImpostor) {
  18502. return this;
  18503. }
  18504. this.physicsImpostor.applyImpulse(force, contactPoint);
  18505. return this;
  18506. };
  18507. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18508. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18509. return this;
  18510. }
  18511. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18512. mainPivot: pivot1,
  18513. connectedPivot: pivot2,
  18514. nativeParams: options
  18515. });
  18516. return this;
  18517. };
  18518. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18519. // Collisions
  18520. /**
  18521. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18522. * Default `false`.
  18523. */
  18524. get: function () {
  18525. return this._checkCollisions;
  18526. },
  18527. set: function (collisionEnabled) {
  18528. this._checkCollisions = collisionEnabled;
  18529. if (this.getScene().workerCollisions) {
  18530. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18531. }
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18537. /**
  18538. * Gets Collider object used to compute collisions (not physics)
  18539. */
  18540. get: function () {
  18541. return this._collider;
  18542. },
  18543. enumerable: true,
  18544. configurable: true
  18545. });
  18546. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18547. var globalPosition = this.getAbsolutePosition();
  18548. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18549. if (!this._collider) {
  18550. this._collider = new BABYLON.Collider();
  18551. }
  18552. this._collider._radius = this.ellipsoid;
  18553. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18554. return this;
  18555. };
  18556. // Submeshes octree
  18557. /**
  18558. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18559. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18560. * Returns an Octree of submeshes.
  18561. */
  18562. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18563. if (maxCapacity === void 0) { maxCapacity = 64; }
  18564. if (maxDepth === void 0) { maxDepth = 2; }
  18565. if (!this._submeshesOctree) {
  18566. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18567. }
  18568. this.computeWorldMatrix(true);
  18569. var boundingInfo = this.getBoundingInfo();
  18570. // Update octree
  18571. var bbox = boundingInfo.boundingBox;
  18572. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18573. return this._submeshesOctree;
  18574. };
  18575. // Collisions
  18576. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18577. this._generatePointsArray();
  18578. if (!this._positions) {
  18579. return this;
  18580. }
  18581. // Transformation
  18582. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18583. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18584. subMesh._lastColliderWorldVertices = [];
  18585. subMesh._trianglePlanes = [];
  18586. var start = subMesh.verticesStart;
  18587. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18588. for (var i = start; i < end; i++) {
  18589. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18590. }
  18591. }
  18592. // Collide
  18593. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18594. if (collider.collisionFound) {
  18595. collider.collidedMesh = this;
  18596. }
  18597. return this;
  18598. };
  18599. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18600. var subMeshes;
  18601. var len;
  18602. // Octrees
  18603. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18604. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18605. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18606. len = intersections.length;
  18607. subMeshes = intersections.data;
  18608. }
  18609. else {
  18610. subMeshes = this.subMeshes;
  18611. len = subMeshes.length;
  18612. }
  18613. for (var index = 0; index < len; index++) {
  18614. var subMesh = subMeshes[index];
  18615. // Bounding test
  18616. if (len > 1 && !subMesh._checkCollision(collider))
  18617. continue;
  18618. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18619. }
  18620. return this;
  18621. };
  18622. AbstractMesh.prototype._checkCollision = function (collider) {
  18623. // Bounding box test
  18624. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18625. return this;
  18626. // Transformation matrix
  18627. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18628. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18629. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18630. return this;
  18631. };
  18632. // Picking
  18633. AbstractMesh.prototype._generatePointsArray = function () {
  18634. return false;
  18635. };
  18636. /**
  18637. * Checks if the passed Ray intersects with the mesh.
  18638. * Returns an object PickingInfo.
  18639. */
  18640. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18641. var pickingInfo = new BABYLON.PickingInfo();
  18642. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18643. return pickingInfo;
  18644. }
  18645. if (!this._generatePointsArray()) {
  18646. return pickingInfo;
  18647. }
  18648. var intersectInfo = null;
  18649. // Octrees
  18650. var subMeshes;
  18651. var len;
  18652. if (this._submeshesOctree && this.useOctreeForPicking) {
  18653. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18654. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18655. len = intersections.length;
  18656. subMeshes = intersections.data;
  18657. }
  18658. else {
  18659. subMeshes = this.subMeshes;
  18660. len = subMeshes.length;
  18661. }
  18662. for (var index = 0; index < len; index++) {
  18663. var subMesh = subMeshes[index];
  18664. // Bounding test
  18665. if (len > 1 && !subMesh.canIntersects(ray))
  18666. continue;
  18667. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18668. if (currentIntersectInfo) {
  18669. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18670. intersectInfo = currentIntersectInfo;
  18671. intersectInfo.subMeshId = index;
  18672. if (fastCheck) {
  18673. break;
  18674. }
  18675. }
  18676. }
  18677. }
  18678. if (intersectInfo) {
  18679. // Get picked point
  18680. var world = this.getWorldMatrix();
  18681. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18682. var direction = ray.direction.clone();
  18683. direction = direction.scale(intersectInfo.distance);
  18684. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18685. var pickedPoint = worldOrigin.add(worldDirection);
  18686. // Return result
  18687. pickingInfo.hit = true;
  18688. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18689. pickingInfo.pickedPoint = pickedPoint;
  18690. pickingInfo.pickedMesh = this;
  18691. pickingInfo.bu = intersectInfo.bu || 0;
  18692. pickingInfo.bv = intersectInfo.bv || 0;
  18693. pickingInfo.faceId = intersectInfo.faceId;
  18694. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18695. return pickingInfo;
  18696. }
  18697. return pickingInfo;
  18698. };
  18699. /**
  18700. * Clones the mesh, used by the class Mesh.
  18701. * Just returns `null` for an AbstractMesh.
  18702. */
  18703. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18704. return null;
  18705. };
  18706. /**
  18707. * Disposes all the mesh submeshes.
  18708. * Returns the AbstractMesh.
  18709. */
  18710. AbstractMesh.prototype.releaseSubMeshes = function () {
  18711. if (this.subMeshes) {
  18712. while (this.subMeshes.length) {
  18713. this.subMeshes[0].dispose();
  18714. }
  18715. }
  18716. else {
  18717. this.subMeshes = new Array();
  18718. }
  18719. return this;
  18720. };
  18721. /**
  18722. * Releases resources associated with this abstract mesh.
  18723. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18724. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18725. */
  18726. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18727. var _this = this;
  18728. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18729. var index;
  18730. // Smart Array Retainers.
  18731. this.getScene().freeActiveMeshes();
  18732. this.getScene().freeRenderingGroups();
  18733. // Action manager
  18734. if (this.actionManager !== undefined && this.actionManager !== null) {
  18735. this.actionManager.dispose();
  18736. this.actionManager = null;
  18737. }
  18738. // Skeleton
  18739. this._skeleton = null;
  18740. // Physics
  18741. if (this.physicsImpostor) {
  18742. this.physicsImpostor.dispose();
  18743. }
  18744. // Intersections in progress
  18745. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18746. var other = this._intersectionsInProgress[index];
  18747. var pos = other._intersectionsInProgress.indexOf(this);
  18748. other._intersectionsInProgress.splice(pos, 1);
  18749. }
  18750. this._intersectionsInProgress = [];
  18751. // Lights
  18752. var lights = this.getScene().lights;
  18753. lights.forEach(function (light) {
  18754. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18755. if (meshIndex !== -1) {
  18756. light.includedOnlyMeshes.splice(meshIndex, 1);
  18757. }
  18758. meshIndex = light.excludedMeshes.indexOf(_this);
  18759. if (meshIndex !== -1) {
  18760. light.excludedMeshes.splice(meshIndex, 1);
  18761. }
  18762. // Shadow generators
  18763. var generator = light.getShadowGenerator();
  18764. if (generator) {
  18765. var shadowMap = generator.getShadowMap();
  18766. if (shadowMap && shadowMap.renderList) {
  18767. meshIndex = shadowMap.renderList.indexOf(_this);
  18768. if (meshIndex !== -1) {
  18769. shadowMap.renderList.splice(meshIndex, 1);
  18770. }
  18771. }
  18772. }
  18773. });
  18774. // Edges
  18775. if (this._edgesRenderer) {
  18776. this._edgesRenderer.dispose();
  18777. this._edgesRenderer = null;
  18778. }
  18779. // SubMeshes
  18780. if (this.getClassName() !== "InstancedMesh") {
  18781. this.releaseSubMeshes();
  18782. }
  18783. // Octree
  18784. var sceneOctree = this.getScene().selectionOctree;
  18785. if (sceneOctree !== undefined && sceneOctree !== null) {
  18786. var index = sceneOctree.dynamicContent.indexOf(this);
  18787. if (index !== -1) {
  18788. sceneOctree.dynamicContent.splice(index, 1);
  18789. }
  18790. }
  18791. // Query
  18792. var engine = this.getScene().getEngine();
  18793. if (this._occlusionQuery) {
  18794. this._isOcclusionQueryInProgress = false;
  18795. engine.deleteQuery(this._occlusionQuery);
  18796. this._occlusionQuery = null;
  18797. }
  18798. // Engine
  18799. engine.wipeCaches();
  18800. // Remove from scene
  18801. this.getScene().removeMesh(this);
  18802. if (disposeMaterialAndTextures) {
  18803. if (this.material) {
  18804. this.material.dispose(false, true);
  18805. }
  18806. }
  18807. if (!doNotRecurse) {
  18808. // Particles
  18809. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18810. if (this.getScene().particleSystems[index].emitter === this) {
  18811. this.getScene().particleSystems[index].dispose();
  18812. index--;
  18813. }
  18814. }
  18815. }
  18816. // facet data
  18817. if (this._facetDataEnabled) {
  18818. this.disableFacetData();
  18819. }
  18820. this.onAfterWorldMatrixUpdateObservable.clear();
  18821. this.onCollideObservable.clear();
  18822. this.onCollisionPositionChangeObservable.clear();
  18823. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18824. };
  18825. /**
  18826. * Adds the passed mesh as a child to the current mesh.
  18827. * Returns the AbstractMesh.
  18828. */
  18829. AbstractMesh.prototype.addChild = function (mesh) {
  18830. mesh.setParent(this);
  18831. return this;
  18832. };
  18833. /**
  18834. * Removes the passed mesh from the current mesh children list.
  18835. * Returns the AbstractMesh.
  18836. */
  18837. AbstractMesh.prototype.removeChild = function (mesh) {
  18838. mesh.setParent(null);
  18839. return this;
  18840. };
  18841. // Facet data
  18842. /**
  18843. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18844. * Returns the AbstractMesh.
  18845. */
  18846. AbstractMesh.prototype._initFacetData = function () {
  18847. if (!this._facetNormals) {
  18848. this._facetNormals = new Array();
  18849. }
  18850. if (!this._facetPositions) {
  18851. this._facetPositions = new Array();
  18852. }
  18853. if (!this._facetPartitioning) {
  18854. this._facetPartitioning = new Array();
  18855. }
  18856. this._facetNb = (this.getIndices().length / 3) | 0;
  18857. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18858. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18859. for (var f = 0; f < this._facetNb; f++) {
  18860. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18861. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18862. }
  18863. this._facetDataEnabled = true;
  18864. return this;
  18865. };
  18866. /**
  18867. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18868. * This method can be called within the render loop.
  18869. * 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.
  18870. * Returns the AbstractMesh.
  18871. */
  18872. AbstractMesh.prototype.updateFacetData = function () {
  18873. if (!this._facetDataEnabled) {
  18874. this._initFacetData();
  18875. }
  18876. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18877. var indices = this.getIndices();
  18878. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18879. var bInfo = this.getBoundingInfo();
  18880. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18881. // init arrays, matrix and sort function on first call
  18882. this._facetDepthSortEnabled = true;
  18883. if (indices instanceof Uint16Array) {
  18884. this._depthSortedIndices = new Uint16Array(indices);
  18885. }
  18886. else if (indices instanceof Uint32Array) {
  18887. this._depthSortedIndices = new Uint32Array(indices);
  18888. }
  18889. else {
  18890. var needs32bits = false;
  18891. for (var i = 0; i < indices.length; i++) {
  18892. if (indices[i] > 65535) {
  18893. needs32bits = true;
  18894. break;
  18895. }
  18896. }
  18897. if (needs32bits) {
  18898. this._depthSortedIndices = new Uint32Array(indices);
  18899. }
  18900. else {
  18901. this._depthSortedIndices = new Uint16Array(indices);
  18902. }
  18903. }
  18904. this._facetDepthSortFunction = function (f1, f2) {
  18905. return (f2.sqDistance - f1.sqDistance);
  18906. };
  18907. if (!this._facetDepthSortFrom) {
  18908. var camera = this.getScene().activeCamera;
  18909. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18910. }
  18911. this._depthSortedFacets = [];
  18912. for (var f = 0; f < this._facetNb; f++) {
  18913. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18914. this._depthSortedFacets.push(depthSortedFacet);
  18915. }
  18916. this._invertedMatrix = BABYLON.Matrix.Identity();
  18917. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18918. }
  18919. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18920. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18921. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18922. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18923. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18924. this._subDiv.max = this._partitioningSubdivisions;
  18925. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18926. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18927. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18928. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18929. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18930. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18931. // set the parameters for ComputeNormals()
  18932. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18933. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18934. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18935. this._facetParameters.bInfo = bInfo;
  18936. this._facetParameters.bbSize = this._bbSize;
  18937. this._facetParameters.subDiv = this._subDiv;
  18938. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18939. this._facetParameters.depthSort = this._facetDepthSort;
  18940. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18941. this.computeWorldMatrix(true);
  18942. this._worldMatrix.invertToRef(this._invertedMatrix);
  18943. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18944. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18945. }
  18946. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18947. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18948. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18949. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18950. var l = (this._depthSortedIndices.length / 3) | 0;
  18951. for (var f = 0; f < l; f++) {
  18952. var sind = this._depthSortedFacets[f].ind;
  18953. this._depthSortedIndices[f * 3] = indices[sind];
  18954. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18955. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18956. }
  18957. this.updateIndices(this._depthSortedIndices);
  18958. }
  18959. return this;
  18960. };
  18961. /**
  18962. * Returns the facetLocalNormals array.
  18963. * The normals are expressed in the mesh local space.
  18964. */
  18965. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18966. if (!this._facetNormals) {
  18967. this.updateFacetData();
  18968. }
  18969. return this._facetNormals;
  18970. };
  18971. /**
  18972. * Returns the facetLocalPositions array.
  18973. * The facet positions are expressed in the mesh local space.
  18974. */
  18975. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18976. if (!this._facetPositions) {
  18977. this.updateFacetData();
  18978. }
  18979. return this._facetPositions;
  18980. };
  18981. /**
  18982. * Returns the facetLocalPartioning array.
  18983. */
  18984. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18985. if (!this._facetPartitioning) {
  18986. this.updateFacetData();
  18987. }
  18988. return this._facetPartitioning;
  18989. };
  18990. /**
  18991. * Returns the i-th facet position in the world system.
  18992. * This method allocates a new Vector3 per call.
  18993. */
  18994. AbstractMesh.prototype.getFacetPosition = function (i) {
  18995. var pos = BABYLON.Vector3.Zero();
  18996. this.getFacetPositionToRef(i, pos);
  18997. return pos;
  18998. };
  18999. /**
  19000. * Sets the reference Vector3 with the i-th facet position in the world system.
  19001. * Returns the AbstractMesh.
  19002. */
  19003. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19004. var localPos = (this.getFacetLocalPositions())[i];
  19005. var world = this.getWorldMatrix();
  19006. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19007. return this;
  19008. };
  19009. /**
  19010. * Returns the i-th facet normal in the world system.
  19011. * This method allocates a new Vector3 per call.
  19012. */
  19013. AbstractMesh.prototype.getFacetNormal = function (i) {
  19014. var norm = BABYLON.Vector3.Zero();
  19015. this.getFacetNormalToRef(i, norm);
  19016. return norm;
  19017. };
  19018. /**
  19019. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19020. * Returns the AbstractMesh.
  19021. */
  19022. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19023. var localNorm = (this.getFacetLocalNormals())[i];
  19024. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19025. return this;
  19026. };
  19027. /**
  19028. * 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).
  19029. */
  19030. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19031. var bInfo = this.getBoundingInfo();
  19032. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19033. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19034. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19035. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19036. return null;
  19037. }
  19038. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19039. };
  19040. /**
  19041. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19042. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19043. * 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.
  19044. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19045. * 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.
  19046. */
  19047. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19048. if (checkFace === void 0) { checkFace = false; }
  19049. if (facing === void 0) { facing = true; }
  19050. var world = this.getWorldMatrix();
  19051. var invMat = BABYLON.Tmp.Matrix[5];
  19052. world.invertToRef(invMat);
  19053. var invVect = BABYLON.Tmp.Vector3[8];
  19054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19055. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19056. if (projected) {
  19057. // tranform the local computed projected vector to world coordinates
  19058. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19059. }
  19060. return closest;
  19061. };
  19062. /**
  19063. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19064. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19065. * 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.
  19066. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19067. * 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.
  19068. */
  19069. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19070. if (checkFace === void 0) { checkFace = false; }
  19071. if (facing === void 0) { facing = true; }
  19072. var closest = null;
  19073. var tmpx = 0.0;
  19074. var tmpy = 0.0;
  19075. var tmpz = 0.0;
  19076. var d = 0.0; // tmp dot facet normal * facet position
  19077. var t0 = 0.0;
  19078. var projx = 0.0;
  19079. var projy = 0.0;
  19080. var projz = 0.0;
  19081. // Get all the facets in the same partitioning block than (x, y, z)
  19082. var facetPositions = this.getFacetLocalPositions();
  19083. var facetNormals = this.getFacetLocalNormals();
  19084. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19085. if (!facetsInBlock) {
  19086. return null;
  19087. }
  19088. // Get the closest facet to (x, y, z)
  19089. var shortest = Number.MAX_VALUE; // init distance vars
  19090. var tmpDistance = shortest;
  19091. var fib; // current facet in the block
  19092. var norm; // current facet normal
  19093. var p0; // current facet barycenter position
  19094. // loop on all the facets in the current partitioning block
  19095. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19096. fib = facetsInBlock[idx];
  19097. norm = facetNormals[fib];
  19098. p0 = facetPositions[fib];
  19099. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19100. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19101. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19102. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19103. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19104. projx = x + norm.x * t0;
  19105. projy = y + norm.y * t0;
  19106. projz = z + norm.z * t0;
  19107. tmpx = projx - x;
  19108. tmpy = projy - y;
  19109. tmpz = projz - z;
  19110. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19111. if (tmpDistance < shortest) {
  19112. shortest = tmpDistance;
  19113. closest = fib;
  19114. if (projected) {
  19115. projected.x = projx;
  19116. projected.y = projy;
  19117. projected.z = projz;
  19118. }
  19119. }
  19120. }
  19121. }
  19122. return closest;
  19123. };
  19124. /**
  19125. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19126. */
  19127. AbstractMesh.prototype.getFacetDataParameters = function () {
  19128. return this._facetParameters;
  19129. };
  19130. /**
  19131. * Disables the feature FacetData and frees the related memory.
  19132. * Returns the AbstractMesh.
  19133. */
  19134. AbstractMesh.prototype.disableFacetData = function () {
  19135. if (this._facetDataEnabled) {
  19136. this._facetDataEnabled = false;
  19137. this._facetPositions = new Array();
  19138. this._facetNormals = new Array();
  19139. this._facetPartitioning = new Array();
  19140. this._facetParameters = null;
  19141. this._depthSortedIndices = new Uint32Array(0);
  19142. }
  19143. return this;
  19144. };
  19145. /**
  19146. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19147. * Returns the mesh.
  19148. */
  19149. AbstractMesh.prototype.updateIndices = function (indices) {
  19150. return this;
  19151. };
  19152. /**
  19153. * The mesh Geometry. Actually used by the Mesh object.
  19154. * Returns a blank geometry object.
  19155. */
  19156. /**
  19157. * Creates new normals data for the mesh.
  19158. * @param updatable.
  19159. */
  19160. AbstractMesh.prototype.createNormals = function (updatable) {
  19161. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19162. var indices = this.getIndices();
  19163. var normals;
  19164. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19165. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19166. }
  19167. else {
  19168. normals = [];
  19169. }
  19170. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19171. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19172. };
  19173. /**
  19174. * Align the mesh with a normal.
  19175. * Returns the mesh.
  19176. */
  19177. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19178. if (!upDirection) {
  19179. upDirection = BABYLON.Axis.Y;
  19180. }
  19181. var axisX = BABYLON.Tmp.Vector3[0];
  19182. var axisZ = BABYLON.Tmp.Vector3[1];
  19183. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19184. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19185. if (this.rotationQuaternion) {
  19186. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19187. }
  19188. else {
  19189. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19190. }
  19191. return this;
  19192. };
  19193. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19194. var engine = this.getEngine();
  19195. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19196. this._isOccluded = false;
  19197. return;
  19198. }
  19199. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19200. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19201. if (isOcclusionQueryAvailable) {
  19202. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19203. this._isOcclusionQueryInProgress = false;
  19204. this._occlusionInternalRetryCounter = 0;
  19205. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19206. }
  19207. else {
  19208. this._occlusionInternalRetryCounter++;
  19209. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19210. this._isOcclusionQueryInProgress = false;
  19211. this._occlusionInternalRetryCounter = 0;
  19212. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19213. // if strict continue the last state of the object.
  19214. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19215. }
  19216. else {
  19217. return;
  19218. }
  19219. }
  19220. }
  19221. var scene = this.getScene();
  19222. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19223. if (!this._occlusionQuery) {
  19224. this._occlusionQuery = engine.createQuery();
  19225. }
  19226. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19227. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19228. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19229. this._isOcclusionQueryInProgress = true;
  19230. };
  19231. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19232. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19233. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19234. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19235. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19236. return AbstractMesh;
  19237. }(BABYLON.TransformNode));
  19238. BABYLON.AbstractMesh = AbstractMesh;
  19239. })(BABYLON || (BABYLON = {}));
  19240. //# sourceMappingURL=babylon.abstractMesh.js.map
  19241. "use strict";
  19242. var BABYLON;
  19243. (function (BABYLON) {
  19244. /**
  19245. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19246. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19247. * 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.
  19248. */
  19249. var Light = /** @class */ (function (_super) {
  19250. __extends(Light, _super);
  19251. /**
  19252. * Creates a Light object in the scene.
  19253. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19254. * @param name The firendly name of the light
  19255. * @param scene The scene the light belongs too
  19256. */
  19257. function Light(name, scene) {
  19258. var _this = _super.call(this, name, scene) || this;
  19259. /**
  19260. * Diffuse gives the basic color to an object.
  19261. */
  19262. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19263. /**
  19264. * Specular produces a highlight color on an object.
  19265. * Note: This is note affecting PBR materials.
  19266. */
  19267. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19268. /**
  19269. * Strength of the light.
  19270. * Note: By default it is define in the framework own unit.
  19271. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19272. */
  19273. _this.intensity = 1.0;
  19274. /**
  19275. * Defines how far from the source the light is impacting in scene units.
  19276. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19277. */
  19278. _this.range = Number.MAX_VALUE;
  19279. /**
  19280. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19281. * of light.
  19282. */
  19283. _this._photometricScale = 1.0;
  19284. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19285. _this._radius = 0.00001;
  19286. /**
  19287. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19288. * exceeding the number allowed of the materials.
  19289. */
  19290. _this.renderPriority = 0;
  19291. /**
  19292. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19293. * the current shadow generator.
  19294. */
  19295. _this.shadowEnabled = true;
  19296. _this._excludeWithLayerMask = 0;
  19297. _this._includeOnlyWithLayerMask = 0;
  19298. _this._lightmapMode = 0;
  19299. /**
  19300. * @ignore Internal use only.
  19301. */
  19302. _this._excludedMeshesIds = new Array();
  19303. /**
  19304. * @ignore Internal use only.
  19305. */
  19306. _this._includedOnlyMeshesIds = new Array();
  19307. _this.getScene().addLight(_this);
  19308. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19309. _this._buildUniformLayout();
  19310. _this.includedOnlyMeshes = new Array();
  19311. _this.excludedMeshes = new Array();
  19312. _this._resyncMeshes();
  19313. return _this;
  19314. }
  19315. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19316. /**
  19317. * If every light affecting the material is in this lightmapMode,
  19318. * material.lightmapTexture adds or multiplies
  19319. * (depends on material.useLightmapAsShadowmap)
  19320. * after every other light calculations.
  19321. */
  19322. get: function () {
  19323. return Light._LIGHTMAP_DEFAULT;
  19324. },
  19325. enumerable: true,
  19326. configurable: true
  19327. });
  19328. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19329. /**
  19330. * material.lightmapTexture as only diffuse lighting from this light
  19331. * adds only specular lighting from this light
  19332. * adds dynamic shadows
  19333. */
  19334. get: function () {
  19335. return Light._LIGHTMAP_SPECULAR;
  19336. },
  19337. enumerable: true,
  19338. configurable: true
  19339. });
  19340. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19341. /**
  19342. * material.lightmapTexture as only lighting
  19343. * no light calculation from this light
  19344. * only adds dynamic shadows from this light
  19345. */
  19346. get: function () {
  19347. return Light._LIGHTMAP_SHADOWSONLY;
  19348. },
  19349. enumerable: true,
  19350. configurable: true
  19351. });
  19352. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19353. /**
  19354. * Each light type uses the default quantity according to its type:
  19355. * point/spot lights use luminous intensity
  19356. * directional lights use illuminance
  19357. */
  19358. get: function () {
  19359. return Light._INTENSITYMODE_AUTOMATIC;
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19365. /**
  19366. * lumen (lm)
  19367. */
  19368. get: function () {
  19369. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19370. },
  19371. enumerable: true,
  19372. configurable: true
  19373. });
  19374. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19375. /**
  19376. * candela (lm/sr)
  19377. */
  19378. get: function () {
  19379. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19380. },
  19381. enumerable: true,
  19382. configurable: true
  19383. });
  19384. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19385. /**
  19386. * lux (lm/m^2)
  19387. */
  19388. get: function () {
  19389. return Light._INTENSITYMODE_ILLUMINANCE;
  19390. },
  19391. enumerable: true,
  19392. configurable: true
  19393. });
  19394. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19395. /**
  19396. * nit (cd/m^2)
  19397. */
  19398. get: function () {
  19399. return Light._INTENSITYMODE_LUMINANCE;
  19400. },
  19401. enumerable: true,
  19402. configurable: true
  19403. });
  19404. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19405. /**
  19406. * Light type const id of the point light.
  19407. */
  19408. get: function () {
  19409. return Light._LIGHTTYPEID_POINTLIGHT;
  19410. },
  19411. enumerable: true,
  19412. configurable: true
  19413. });
  19414. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19415. /**
  19416. * Light type const id of the directional light.
  19417. */
  19418. get: function () {
  19419. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19420. },
  19421. enumerable: true,
  19422. configurable: true
  19423. });
  19424. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19425. /**
  19426. * Light type const id of the spot light.
  19427. */
  19428. get: function () {
  19429. return Light._LIGHTTYPEID_SPOTLIGHT;
  19430. },
  19431. enumerable: true,
  19432. configurable: true
  19433. });
  19434. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19435. /**
  19436. * Light type const id of the hemispheric light.
  19437. */
  19438. get: function () {
  19439. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19440. },
  19441. enumerable: true,
  19442. configurable: true
  19443. });
  19444. Object.defineProperty(Light.prototype, "intensityMode", {
  19445. /**
  19446. * Gets the photometric scale used to interpret the intensity.
  19447. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19448. */
  19449. get: function () {
  19450. return this._intensityMode;
  19451. },
  19452. /**
  19453. * Sets the photometric scale used to interpret the intensity.
  19454. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19455. */
  19456. set: function (value) {
  19457. this._intensityMode = value;
  19458. this._computePhotometricScale();
  19459. },
  19460. enumerable: true,
  19461. configurable: true
  19462. });
  19463. ;
  19464. ;
  19465. Object.defineProperty(Light.prototype, "radius", {
  19466. /**
  19467. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19468. */
  19469. get: function () {
  19470. return this._radius;
  19471. },
  19472. /**
  19473. * sets the light radius used by PBR Materials to simulate soft area lights.
  19474. */
  19475. set: function (value) {
  19476. this._radius = value;
  19477. this._computePhotometricScale();
  19478. },
  19479. enumerable: true,
  19480. configurable: true
  19481. });
  19482. ;
  19483. ;
  19484. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19485. /**
  19486. * Gets the only meshes impacted by this light.
  19487. */
  19488. get: function () {
  19489. return this._includedOnlyMeshes;
  19490. },
  19491. /**
  19492. * Sets the only meshes impacted by this light.
  19493. */
  19494. set: function (value) {
  19495. this._includedOnlyMeshes = value;
  19496. this._hookArrayForIncludedOnly(value);
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19502. /**
  19503. * Gets the meshes not impacted by this light.
  19504. */
  19505. get: function () {
  19506. return this._excludedMeshes;
  19507. },
  19508. /**
  19509. * Sets the meshes not impacted by this light.
  19510. */
  19511. set: function (value) {
  19512. this._excludedMeshes = value;
  19513. this._hookArrayForExcluded(value);
  19514. },
  19515. enumerable: true,
  19516. configurable: true
  19517. });
  19518. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19519. /**
  19520. * Gets the layer id use to find what meshes are not impacted by the light.
  19521. * Inactive if 0
  19522. */
  19523. get: function () {
  19524. return this._excludeWithLayerMask;
  19525. },
  19526. /**
  19527. * Sets the layer id use to find what meshes are not impacted by the light.
  19528. * Inactive if 0
  19529. */
  19530. set: function (value) {
  19531. this._excludeWithLayerMask = value;
  19532. this._resyncMeshes();
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19538. /**
  19539. * Gets the layer id use to find what meshes are impacted by the light.
  19540. * Inactive if 0
  19541. */
  19542. get: function () {
  19543. return this._includeOnlyWithLayerMask;
  19544. },
  19545. /**
  19546. * Sets the layer id use to find what meshes are impacted by the light.
  19547. * Inactive if 0
  19548. */
  19549. set: function (value) {
  19550. this._includeOnlyWithLayerMask = value;
  19551. this._resyncMeshes();
  19552. },
  19553. enumerable: true,
  19554. configurable: true
  19555. });
  19556. Object.defineProperty(Light.prototype, "lightmapMode", {
  19557. /**
  19558. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19559. */
  19560. get: function () {
  19561. return this._lightmapMode;
  19562. },
  19563. /**
  19564. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19565. */
  19566. set: function (value) {
  19567. if (this._lightmapMode === value) {
  19568. return;
  19569. }
  19570. this._lightmapMode = value;
  19571. this._markMeshesAsLightDirty();
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. /**
  19577. * Returns the string "Light".
  19578. * @returns the class name
  19579. */
  19580. Light.prototype.getClassName = function () {
  19581. return "Light";
  19582. };
  19583. /**
  19584. * Converts the light information to a readable string for debug purpose.
  19585. * @param fullDetails Supports for multiple levels of logging within scene loading
  19586. * @returns the human readable light info
  19587. */
  19588. Light.prototype.toString = function (fullDetails) {
  19589. var ret = "Name: " + this.name;
  19590. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19591. if (this.animations) {
  19592. for (var i = 0; i < this.animations.length; i++) {
  19593. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19594. }
  19595. }
  19596. if (fullDetails) {
  19597. }
  19598. return ret;
  19599. };
  19600. /**
  19601. * Set the enabled state of this node.
  19602. * @param value - the new enabled state
  19603. */
  19604. Light.prototype.setEnabled = function (value) {
  19605. _super.prototype.setEnabled.call(this, value);
  19606. this._resyncMeshes();
  19607. };
  19608. /**
  19609. * Returns the Light associated shadow generator if any.
  19610. * @return the associated shadow generator.
  19611. */
  19612. Light.prototype.getShadowGenerator = function () {
  19613. return this._shadowGenerator;
  19614. };
  19615. /**
  19616. * Returns a Vector3, the absolute light position in the World.
  19617. * @returns the world space position of the light
  19618. */
  19619. Light.prototype.getAbsolutePosition = function () {
  19620. return BABYLON.Vector3.Zero();
  19621. };
  19622. /**
  19623. * Specifies if the light will affect the passed mesh.
  19624. * @param mesh The mesh to test against the light
  19625. * @return true the mesh is affected otherwise, false.
  19626. */
  19627. Light.prototype.canAffectMesh = function (mesh) {
  19628. if (!mesh) {
  19629. return true;
  19630. }
  19631. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19632. return false;
  19633. }
  19634. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19635. return false;
  19636. }
  19637. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19638. return false;
  19639. }
  19640. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19641. return false;
  19642. }
  19643. return true;
  19644. };
  19645. /**
  19646. * Computes and Returns the light World matrix.
  19647. * @returns the world matrix
  19648. */
  19649. Light.prototype.getWorldMatrix = function () {
  19650. this._currentRenderId = this.getScene().getRenderId();
  19651. this._childRenderId = this._currentRenderId;
  19652. var worldMatrix = this._getWorldMatrix();
  19653. if (this.parent && this.parent.getWorldMatrix) {
  19654. if (!this._parentedWorldMatrix) {
  19655. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19656. }
  19657. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19658. this._markSyncedWithParent();
  19659. return this._parentedWorldMatrix;
  19660. }
  19661. return worldMatrix;
  19662. };
  19663. /**
  19664. * Sort function to order lights for rendering.
  19665. * @param a First Light object to compare to second.
  19666. * @param b Second Light object to compare first.
  19667. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19668. */
  19669. Light.CompareLightsPriority = function (a, b) {
  19670. //shadow-casting lights have priority over non-shadow-casting lights
  19671. //the renderPrioirty is a secondary sort criterion
  19672. if (a.shadowEnabled !== b.shadowEnabled) {
  19673. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19674. }
  19675. return b.renderPriority - a.renderPriority;
  19676. };
  19677. /**
  19678. * Releases resources associated with this node.
  19679. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19680. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19681. */
  19682. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19683. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19684. if (this._shadowGenerator) {
  19685. this._shadowGenerator.dispose();
  19686. this._shadowGenerator = null;
  19687. }
  19688. // Animations
  19689. this.getScene().stopAnimation(this);
  19690. // Remove from meshes
  19691. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19692. var mesh = _a[_i];
  19693. mesh._removeLightSource(this);
  19694. }
  19695. this._uniformBuffer.dispose();
  19696. // Remove from scene
  19697. this.getScene().removeLight(this);
  19698. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19699. };
  19700. /**
  19701. * Returns the light type ID (integer).
  19702. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19703. */
  19704. Light.prototype.getTypeID = function () {
  19705. return 0;
  19706. };
  19707. /**
  19708. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19709. * @returns the scaled intensity in intensity mode unit
  19710. */
  19711. Light.prototype.getScaledIntensity = function () {
  19712. return this._photometricScale * this.intensity;
  19713. };
  19714. /**
  19715. * Returns a new Light object, named "name", from the current one.
  19716. * @param name The name of the cloned light
  19717. * @returns the new created light
  19718. */
  19719. Light.prototype.clone = function (name) {
  19720. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19721. if (!constructor) {
  19722. return null;
  19723. }
  19724. return BABYLON.SerializationHelper.Clone(constructor, this);
  19725. };
  19726. /**
  19727. * Serializes the current light into a Serialization object.
  19728. * @returns the serialized object.
  19729. */
  19730. Light.prototype.serialize = function () {
  19731. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19732. // Type
  19733. serializationObject.type = this.getTypeID();
  19734. // Parent
  19735. if (this.parent) {
  19736. serializationObject.parentId = this.parent.id;
  19737. }
  19738. // Inclusion / exclusions
  19739. if (this.excludedMeshes.length > 0) {
  19740. serializationObject.excludedMeshesIds = [];
  19741. this.excludedMeshes.forEach(function (mesh) {
  19742. serializationObject.excludedMeshesIds.push(mesh.id);
  19743. });
  19744. }
  19745. if (this.includedOnlyMeshes.length > 0) {
  19746. serializationObject.includedOnlyMeshesIds = [];
  19747. this.includedOnlyMeshes.forEach(function (mesh) {
  19748. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19749. });
  19750. }
  19751. // Animations
  19752. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19753. serializationObject.ranges = this.serializeAnimationRanges();
  19754. return serializationObject;
  19755. };
  19756. /**
  19757. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19758. * This new light is named "name" and added to the passed scene.
  19759. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19760. * @param name The friendly name of the light
  19761. * @param scene The scene the new light will belong to
  19762. * @returns the constructor function
  19763. */
  19764. Light.GetConstructorFromName = function (type, name, scene) {
  19765. switch (type) {
  19766. case 0:
  19767. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19768. case 1:
  19769. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19770. case 2:
  19771. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19772. case 3:
  19773. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19774. }
  19775. return null;
  19776. };
  19777. /**
  19778. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19779. * @param parsedLight The JSON representation of the light
  19780. * @param scene The scene to create the parsed light in
  19781. * @returns the created light after parsing
  19782. */
  19783. Light.Parse = function (parsedLight, scene) {
  19784. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19785. if (!constructor) {
  19786. return null;
  19787. }
  19788. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19789. // Inclusion / exclusions
  19790. if (parsedLight.excludedMeshesIds) {
  19791. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19792. }
  19793. if (parsedLight.includedOnlyMeshesIds) {
  19794. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19795. }
  19796. // Parent
  19797. if (parsedLight.parentId) {
  19798. light._waitingParentId = parsedLight.parentId;
  19799. }
  19800. // Animations
  19801. if (parsedLight.animations) {
  19802. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19803. var parsedAnimation = parsedLight.animations[animationIndex];
  19804. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19805. }
  19806. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19807. }
  19808. if (parsedLight.autoAnimate) {
  19809. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19810. }
  19811. return light;
  19812. };
  19813. Light.prototype._hookArrayForExcluded = function (array) {
  19814. var _this = this;
  19815. var oldPush = array.push;
  19816. array.push = function () {
  19817. var items = [];
  19818. for (var _i = 0; _i < arguments.length; _i++) {
  19819. items[_i] = arguments[_i];
  19820. }
  19821. var result = oldPush.apply(array, items);
  19822. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19823. var item = items_1[_a];
  19824. item._resyncLighSource(_this);
  19825. }
  19826. return result;
  19827. };
  19828. var oldSplice = array.splice;
  19829. array.splice = function (index, deleteCount) {
  19830. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19831. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19832. var item = deleted_1[_i];
  19833. item._resyncLighSource(_this);
  19834. }
  19835. return deleted;
  19836. };
  19837. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19838. var item = array_1[_i];
  19839. item._resyncLighSource(this);
  19840. }
  19841. };
  19842. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19843. var _this = this;
  19844. var oldPush = array.push;
  19845. array.push = function () {
  19846. var items = [];
  19847. for (var _i = 0; _i < arguments.length; _i++) {
  19848. items[_i] = arguments[_i];
  19849. }
  19850. var result = oldPush.apply(array, items);
  19851. _this._resyncMeshes();
  19852. return result;
  19853. };
  19854. var oldSplice = array.splice;
  19855. array.splice = function (index, deleteCount) {
  19856. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19857. _this._resyncMeshes();
  19858. return deleted;
  19859. };
  19860. this._resyncMeshes();
  19861. };
  19862. Light.prototype._resyncMeshes = function () {
  19863. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19864. var mesh = _a[_i];
  19865. mesh._resyncLighSource(this);
  19866. }
  19867. };
  19868. /**
  19869. * Forces the meshes to update their light related information in their rendering used effects
  19870. * @ignore Internal Use Only
  19871. */
  19872. Light.prototype._markMeshesAsLightDirty = function () {
  19873. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19874. var mesh = _a[_i];
  19875. if (mesh._lightSources.indexOf(this) !== -1) {
  19876. mesh._markSubMeshesAsLightDirty();
  19877. }
  19878. }
  19879. };
  19880. /**
  19881. * Recomputes the cached photometric scale if needed.
  19882. */
  19883. Light.prototype._computePhotometricScale = function () {
  19884. this._photometricScale = this._getPhotometricScale();
  19885. this.getScene().resetCachedMaterial();
  19886. };
  19887. /**
  19888. * Returns the Photometric Scale according to the light type and intensity mode.
  19889. */
  19890. Light.prototype._getPhotometricScale = function () {
  19891. var photometricScale = 0.0;
  19892. var lightTypeID = this.getTypeID();
  19893. //get photometric mode
  19894. var photometricMode = this.intensityMode;
  19895. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19896. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19897. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19898. }
  19899. else {
  19900. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19901. }
  19902. }
  19903. //compute photometric scale
  19904. switch (lightTypeID) {
  19905. case Light.LIGHTTYPEID_POINTLIGHT:
  19906. case Light.LIGHTTYPEID_SPOTLIGHT:
  19907. switch (photometricMode) {
  19908. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19909. photometricScale = 1.0 / (4.0 * Math.PI);
  19910. break;
  19911. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19912. photometricScale = 1.0;
  19913. break;
  19914. case Light.INTENSITYMODE_LUMINANCE:
  19915. photometricScale = this.radius * this.radius;
  19916. break;
  19917. }
  19918. break;
  19919. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19920. switch (photometricMode) {
  19921. case Light.INTENSITYMODE_ILLUMINANCE:
  19922. photometricScale = 1.0;
  19923. break;
  19924. case Light.INTENSITYMODE_LUMINANCE:
  19925. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19926. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19927. var apexAngleRadians = this.radius;
  19928. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19929. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19930. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19931. photometricScale = solidAngle;
  19932. break;
  19933. }
  19934. break;
  19935. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19936. // No fall off in hemisperic light.
  19937. photometricScale = 1.0;
  19938. break;
  19939. }
  19940. return photometricScale;
  19941. };
  19942. /**
  19943. * Reorder the light in the scene according to their defined priority.
  19944. * @ignore Internal Use Only
  19945. */
  19946. Light.prototype._reorderLightsInScene = function () {
  19947. var scene = this.getScene();
  19948. if (this._renderPriority != 0) {
  19949. scene.requireLightSorting = true;
  19950. }
  19951. this.getScene().sortLightsByPriority();
  19952. };
  19953. //lightmapMode Consts
  19954. Light._LIGHTMAP_DEFAULT = 0;
  19955. Light._LIGHTMAP_SPECULAR = 1;
  19956. Light._LIGHTMAP_SHADOWSONLY = 2;
  19957. // Intensity Mode Consts
  19958. Light._INTENSITYMODE_AUTOMATIC = 0;
  19959. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19960. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19961. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19962. Light._INTENSITYMODE_LUMINANCE = 4;
  19963. // Light types ids const.
  19964. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19965. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19966. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19967. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19968. __decorate([
  19969. BABYLON.serializeAsColor3()
  19970. ], Light.prototype, "diffuse", void 0);
  19971. __decorate([
  19972. BABYLON.serializeAsColor3()
  19973. ], Light.prototype, "specular", void 0);
  19974. __decorate([
  19975. BABYLON.serialize()
  19976. ], Light.prototype, "intensity", void 0);
  19977. __decorate([
  19978. BABYLON.serialize()
  19979. ], Light.prototype, "range", void 0);
  19980. __decorate([
  19981. BABYLON.serialize()
  19982. ], Light.prototype, "intensityMode", null);
  19983. __decorate([
  19984. BABYLON.serialize()
  19985. ], Light.prototype, "radius", null);
  19986. __decorate([
  19987. BABYLON.serialize()
  19988. ], Light.prototype, "_renderPriority", void 0);
  19989. __decorate([
  19990. BABYLON.expandToProperty("_reorderLightsInScene")
  19991. ], Light.prototype, "renderPriority", void 0);
  19992. __decorate([
  19993. BABYLON.serialize()
  19994. ], Light.prototype, "shadowEnabled", void 0);
  19995. __decorate([
  19996. BABYLON.serialize("excludeWithLayerMask")
  19997. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19998. __decorate([
  19999. BABYLON.serialize("includeOnlyWithLayerMask")
  20000. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20001. __decorate([
  20002. BABYLON.serialize("lightmapMode")
  20003. ], Light.prototype, "_lightmapMode", void 0);
  20004. return Light;
  20005. }(BABYLON.Node));
  20006. BABYLON.Light = Light;
  20007. })(BABYLON || (BABYLON = {}));
  20008. //# sourceMappingURL=babylon.light.js.map
  20009. "use strict";
  20010. var BABYLON;
  20011. (function (BABYLON) {
  20012. var Camera = /** @class */ (function (_super) {
  20013. __extends(Camera, _super);
  20014. function Camera(name, position, scene) {
  20015. var _this = _super.call(this, name, scene) || this;
  20016. /**
  20017. * The vector the camera should consider as up.
  20018. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20019. */
  20020. _this.upVector = BABYLON.Vector3.Up();
  20021. _this.orthoLeft = null;
  20022. _this.orthoRight = null;
  20023. _this.orthoBottom = null;
  20024. _this.orthoTop = null;
  20025. /**
  20026. * FOV is set in Radians. (default is 0.8)
  20027. */
  20028. _this.fov = 0.8;
  20029. _this.minZ = 1;
  20030. _this.maxZ = 10000.0;
  20031. _this.inertia = 0.9;
  20032. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20033. _this.isIntermediate = false;
  20034. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20035. /**
  20036. * Restricts the camera to viewing objects with the same layerMask.
  20037. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20038. */
  20039. _this.layerMask = 0x0FFFFFFF;
  20040. /**
  20041. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20042. */
  20043. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20044. // Camera rig members
  20045. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20046. _this._rigCameras = new Array();
  20047. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20048. _this._skipRendering = false;
  20049. _this.customRenderTargets = new Array();
  20050. // Observables
  20051. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20052. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20053. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20054. _this.onRestoreStateObservable = new BABYLON.Observable();
  20055. // Cache
  20056. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20057. _this._projectionMatrix = new BABYLON.Matrix();
  20058. _this._doNotComputeProjectionMatrix = false;
  20059. _this._postProcesses = new Array();
  20060. _this._transformMatrix = BABYLON.Matrix.Zero();
  20061. _this._activeMeshes = new BABYLON.SmartArray(256);
  20062. _this._globalPosition = BABYLON.Vector3.Zero();
  20063. _this._refreshFrustumPlanes = true;
  20064. _this.getScene().addCamera(_this);
  20065. if (!_this.getScene().activeCamera) {
  20066. _this.getScene().activeCamera = _this;
  20067. }
  20068. _this.position = position;
  20069. return _this;
  20070. }
  20071. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20072. get: function () {
  20073. return Camera._PERSPECTIVE_CAMERA;
  20074. },
  20075. enumerable: true,
  20076. configurable: true
  20077. });
  20078. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20079. get: function () {
  20080. return Camera._ORTHOGRAPHIC_CAMERA;
  20081. },
  20082. enumerable: true,
  20083. configurable: true
  20084. });
  20085. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20086. /**
  20087. * This is the default FOV mode for perspective cameras.
  20088. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20089. *
  20090. */
  20091. get: function () {
  20092. return Camera._FOVMODE_VERTICAL_FIXED;
  20093. },
  20094. enumerable: true,
  20095. configurable: true
  20096. });
  20097. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20098. /**
  20099. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20100. *
  20101. */
  20102. get: function () {
  20103. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20104. },
  20105. enumerable: true,
  20106. configurable: true
  20107. });
  20108. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20109. get: function () {
  20110. return Camera._RIG_MODE_NONE;
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20116. get: function () {
  20117. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20123. get: function () {
  20124. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20125. },
  20126. enumerable: true,
  20127. configurable: true
  20128. });
  20129. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20130. get: function () {
  20131. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20137. get: function () {
  20138. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20144. get: function () {
  20145. return Camera._RIG_MODE_VR;
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20151. get: function () {
  20152. return Camera._RIG_MODE_WEBVR;
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. /**
  20158. * Store current camera state (fov, position, etc..)
  20159. */
  20160. Camera.prototype.storeState = function () {
  20161. this._stateStored = true;
  20162. this._storedFov = this.fov;
  20163. return this;
  20164. };
  20165. /**
  20166. * Restores the camera state values if it has been stored. You must call storeState() first
  20167. */
  20168. Camera.prototype._restoreStateValues = function () {
  20169. if (!this._stateStored) {
  20170. return false;
  20171. }
  20172. this.fov = this._storedFov;
  20173. return true;
  20174. };
  20175. /**
  20176. * Restored camera state. You must call storeState() first
  20177. */
  20178. Camera.prototype.restoreState = function () {
  20179. if (this._restoreStateValues()) {
  20180. this.onRestoreStateObservable.notifyObservers(this);
  20181. return true;
  20182. }
  20183. return false;
  20184. };
  20185. Camera.prototype.getClassName = function () {
  20186. return "Camera";
  20187. };
  20188. /**
  20189. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20190. */
  20191. Camera.prototype.toString = function (fullDetails) {
  20192. var ret = "Name: " + this.name;
  20193. ret += ", type: " + this.getClassName();
  20194. if (this.animations) {
  20195. for (var i = 0; i < this.animations.length; i++) {
  20196. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20197. }
  20198. }
  20199. if (fullDetails) {
  20200. }
  20201. return ret;
  20202. };
  20203. Object.defineProperty(Camera.prototype, "globalPosition", {
  20204. get: function () {
  20205. return this._globalPosition;
  20206. },
  20207. enumerable: true,
  20208. configurable: true
  20209. });
  20210. Camera.prototype.getActiveMeshes = function () {
  20211. return this._activeMeshes;
  20212. };
  20213. Camera.prototype.isActiveMesh = function (mesh) {
  20214. return (this._activeMeshes.indexOf(mesh) !== -1);
  20215. };
  20216. /**
  20217. * Is this camera ready to be used/rendered
  20218. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  20219. * @return true if the camera is ready
  20220. */
  20221. Camera.prototype.isReady = function (completeCheck) {
  20222. if (completeCheck === void 0) { completeCheck = false; }
  20223. if (completeCheck) {
  20224. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  20225. var pp = _a[_i];
  20226. if (pp && !pp.isReady()) {
  20227. return false;
  20228. }
  20229. }
  20230. }
  20231. return _super.prototype.isReady.call(this, completeCheck);
  20232. };
  20233. //Cache
  20234. Camera.prototype._initCache = function () {
  20235. _super.prototype._initCache.call(this);
  20236. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20237. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20238. this._cache.mode = undefined;
  20239. this._cache.minZ = undefined;
  20240. this._cache.maxZ = undefined;
  20241. this._cache.fov = undefined;
  20242. this._cache.fovMode = undefined;
  20243. this._cache.aspectRatio = undefined;
  20244. this._cache.orthoLeft = undefined;
  20245. this._cache.orthoRight = undefined;
  20246. this._cache.orthoBottom = undefined;
  20247. this._cache.orthoTop = undefined;
  20248. this._cache.renderWidth = undefined;
  20249. this._cache.renderHeight = undefined;
  20250. };
  20251. Camera.prototype._updateCache = function (ignoreParentClass) {
  20252. if (!ignoreParentClass) {
  20253. _super.prototype._updateCache.call(this);
  20254. }
  20255. this._cache.position.copyFrom(this.position);
  20256. this._cache.upVector.copyFrom(this.upVector);
  20257. };
  20258. // Synchronized
  20259. Camera.prototype._isSynchronized = function () {
  20260. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20261. };
  20262. Camera.prototype._isSynchronizedViewMatrix = function () {
  20263. if (!_super.prototype._isSynchronized.call(this))
  20264. return false;
  20265. return this._cache.position.equals(this.position)
  20266. && this._cache.upVector.equals(this.upVector)
  20267. && this.isSynchronizedWithParent();
  20268. };
  20269. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20270. var check = this._cache.mode === this.mode
  20271. && this._cache.minZ === this.minZ
  20272. && this._cache.maxZ === this.maxZ;
  20273. if (!check) {
  20274. return false;
  20275. }
  20276. var engine = this.getEngine();
  20277. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20278. check = this._cache.fov === this.fov
  20279. && this._cache.fovMode === this.fovMode
  20280. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20281. }
  20282. else {
  20283. check = this._cache.orthoLeft === this.orthoLeft
  20284. && this._cache.orthoRight === this.orthoRight
  20285. && this._cache.orthoBottom === this.orthoBottom
  20286. && this._cache.orthoTop === this.orthoTop
  20287. && this._cache.renderWidth === engine.getRenderWidth()
  20288. && this._cache.renderHeight === engine.getRenderHeight();
  20289. }
  20290. return check;
  20291. };
  20292. // Controls
  20293. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20294. };
  20295. Camera.prototype.detachControl = function (element) {
  20296. };
  20297. Camera.prototype.update = function () {
  20298. this._checkInputs();
  20299. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20300. this._updateRigCameras();
  20301. }
  20302. };
  20303. Camera.prototype._checkInputs = function () {
  20304. this.onAfterCheckInputsObservable.notifyObservers(this);
  20305. };
  20306. Object.defineProperty(Camera.prototype, "rigCameras", {
  20307. get: function () {
  20308. return this._rigCameras;
  20309. },
  20310. enumerable: true,
  20311. configurable: true
  20312. });
  20313. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20314. get: function () {
  20315. return this._rigPostProcess;
  20316. },
  20317. enumerable: true,
  20318. configurable: true
  20319. });
  20320. /**
  20321. * Internal, gets the first post proces.
  20322. * @returns the first post process to be run on this camera.
  20323. */
  20324. Camera.prototype._getFirstPostProcess = function () {
  20325. for (var pp in this._postProcesses) {
  20326. if (this._postProcesses[pp] !== null) {
  20327. return this._postProcesses[pp];
  20328. }
  20329. }
  20330. return null;
  20331. };
  20332. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20333. // invalidate framebuffer
  20334. var firstPostProcess = this._getFirstPostProcess();
  20335. if (firstPostProcess) {
  20336. firstPostProcess.markTextureDirty();
  20337. }
  20338. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20339. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20340. var cam = this._rigCameras[i];
  20341. var rigPostProcess = cam._rigPostProcess;
  20342. // for VR rig, there does not have to be a post process
  20343. if (rigPostProcess) {
  20344. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20345. if (isPass) {
  20346. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20347. cam.isIntermediate = this._postProcesses.length === 0;
  20348. }
  20349. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20350. rigPostProcess.markTextureDirty();
  20351. }
  20352. else {
  20353. cam._postProcesses = this._postProcesses.slice(0);
  20354. }
  20355. }
  20356. };
  20357. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20358. if (insertAt === void 0) { insertAt = null; }
  20359. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20360. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20361. return 0;
  20362. }
  20363. if (insertAt == null || insertAt < 0) {
  20364. this._postProcesses.push(postProcess);
  20365. }
  20366. else if (this._postProcesses[insertAt] === null) {
  20367. this._postProcesses[insertAt] = postProcess;
  20368. }
  20369. else {
  20370. this._postProcesses.splice(insertAt, 0, postProcess);
  20371. }
  20372. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20373. return this._postProcesses.indexOf(postProcess);
  20374. };
  20375. Camera.prototype.detachPostProcess = function (postProcess) {
  20376. var idx = this._postProcesses.indexOf(postProcess);
  20377. if (idx !== -1) {
  20378. this._postProcesses[idx] = null;
  20379. }
  20380. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20381. };
  20382. Camera.prototype.getWorldMatrix = function () {
  20383. if (!this._worldMatrix) {
  20384. this._worldMatrix = BABYLON.Matrix.Identity();
  20385. }
  20386. var viewMatrix = this.getViewMatrix();
  20387. viewMatrix.invertToRef(this._worldMatrix);
  20388. return this._worldMatrix;
  20389. };
  20390. Camera.prototype._getViewMatrix = function () {
  20391. return BABYLON.Matrix.Identity();
  20392. };
  20393. Camera.prototype.getViewMatrix = function (force) {
  20394. if (!force && this._isSynchronizedViewMatrix()) {
  20395. return this._computedViewMatrix;
  20396. }
  20397. this.updateCache();
  20398. this._computedViewMatrix = this._getViewMatrix();
  20399. this._currentRenderId = this.getScene().getRenderId();
  20400. this._childRenderId = this._currentRenderId;
  20401. this._refreshFrustumPlanes = true;
  20402. if (!this.parent || !this.parent.getWorldMatrix) {
  20403. this._globalPosition.copyFrom(this.position);
  20404. }
  20405. else {
  20406. if (!this._worldMatrix) {
  20407. this._worldMatrix = BABYLON.Matrix.Identity();
  20408. }
  20409. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20410. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20411. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20412. this._computedViewMatrix.invert();
  20413. this._markSyncedWithParent();
  20414. }
  20415. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20416. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20417. }
  20418. this.onViewMatrixChangedObservable.notifyObservers(this);
  20419. return this._computedViewMatrix;
  20420. };
  20421. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20422. this._doNotComputeProjectionMatrix = true;
  20423. if (projection !== undefined) {
  20424. this._projectionMatrix = projection;
  20425. }
  20426. };
  20427. ;
  20428. Camera.prototype.unfreezeProjectionMatrix = function () {
  20429. this._doNotComputeProjectionMatrix = false;
  20430. };
  20431. ;
  20432. Camera.prototype.getProjectionMatrix = function (force) {
  20433. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20434. return this._projectionMatrix;
  20435. }
  20436. // Cache
  20437. this._cache.mode = this.mode;
  20438. this._cache.minZ = this.minZ;
  20439. this._cache.maxZ = this.maxZ;
  20440. // Matrix
  20441. this._refreshFrustumPlanes = true;
  20442. var engine = this.getEngine();
  20443. var scene = this.getScene();
  20444. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20445. this._cache.fov = this.fov;
  20446. this._cache.fovMode = this.fovMode;
  20447. this._cache.aspectRatio = engine.getAspectRatio(this);
  20448. if (this.minZ <= 0) {
  20449. this.minZ = 0.1;
  20450. }
  20451. if (scene.useRightHandedSystem) {
  20452. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20453. }
  20454. else {
  20455. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20456. }
  20457. }
  20458. else {
  20459. var halfWidth = engine.getRenderWidth() / 2.0;
  20460. var halfHeight = engine.getRenderHeight() / 2.0;
  20461. if (scene.useRightHandedSystem) {
  20462. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20463. }
  20464. else {
  20465. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20466. }
  20467. this._cache.orthoLeft = this.orthoLeft;
  20468. this._cache.orthoRight = this.orthoRight;
  20469. this._cache.orthoBottom = this.orthoBottom;
  20470. this._cache.orthoTop = this.orthoTop;
  20471. this._cache.renderWidth = engine.getRenderWidth();
  20472. this._cache.renderHeight = engine.getRenderHeight();
  20473. }
  20474. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20475. return this._projectionMatrix;
  20476. };
  20477. Camera.prototype.getTranformationMatrix = function () {
  20478. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20479. return this._transformMatrix;
  20480. };
  20481. Camera.prototype.updateFrustumPlanes = function () {
  20482. if (!this._refreshFrustumPlanes) {
  20483. return;
  20484. }
  20485. this.getTranformationMatrix();
  20486. if (!this._frustumPlanes) {
  20487. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20488. }
  20489. else {
  20490. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20491. }
  20492. this._refreshFrustumPlanes = false;
  20493. };
  20494. Camera.prototype.isInFrustum = function (target) {
  20495. this.updateFrustumPlanes();
  20496. return target.isInFrustum(this._frustumPlanes);
  20497. };
  20498. Camera.prototype.isCompletelyInFrustum = function (target) {
  20499. this.updateFrustumPlanes();
  20500. return target.isCompletelyInFrustum(this._frustumPlanes);
  20501. };
  20502. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20503. if (length === void 0) { length = 100; }
  20504. if (!transform) {
  20505. transform = this.getWorldMatrix();
  20506. }
  20507. if (!origin) {
  20508. origin = this.position;
  20509. }
  20510. var forward = new BABYLON.Vector3(0, 0, 1);
  20511. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20512. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20513. return new BABYLON.Ray(origin, direction, length);
  20514. };
  20515. /**
  20516. * Releases resources associated with this node.
  20517. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20518. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20519. */
  20520. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20521. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20522. // Observables
  20523. this.onViewMatrixChangedObservable.clear();
  20524. this.onProjectionMatrixChangedObservable.clear();
  20525. this.onAfterCheckInputsObservable.clear();
  20526. this.onRestoreStateObservable.clear();
  20527. // Inputs
  20528. if (this.inputs) {
  20529. this.inputs.clear();
  20530. }
  20531. // Animations
  20532. this.getScene().stopAnimation(this);
  20533. // Remove from scene
  20534. this.getScene().removeCamera(this);
  20535. while (this._rigCameras.length > 0) {
  20536. var camera = this._rigCameras.pop();
  20537. if (camera) {
  20538. camera.dispose();
  20539. }
  20540. }
  20541. // Postprocesses
  20542. if (this._rigPostProcess) {
  20543. this._rigPostProcess.dispose(this);
  20544. this._rigPostProcess = null;
  20545. this._postProcesses = [];
  20546. }
  20547. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20548. this._rigPostProcess = null;
  20549. this._postProcesses = [];
  20550. }
  20551. else {
  20552. var i = this._postProcesses.length;
  20553. while (--i >= 0) {
  20554. var postProcess = this._postProcesses[i];
  20555. if (postProcess) {
  20556. postProcess.dispose(this);
  20557. }
  20558. }
  20559. }
  20560. // Render targets
  20561. var i = this.customRenderTargets.length;
  20562. while (--i >= 0) {
  20563. this.customRenderTargets[i].dispose();
  20564. }
  20565. this.customRenderTargets = [];
  20566. // Active Meshes
  20567. this._activeMeshes.dispose();
  20568. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20569. };
  20570. Object.defineProperty(Camera.prototype, "leftCamera", {
  20571. // ---- Camera rigs section ----
  20572. get: function () {
  20573. if (this._rigCameras.length < 1) {
  20574. return null;
  20575. }
  20576. return this._rigCameras[0];
  20577. },
  20578. enumerable: true,
  20579. configurable: true
  20580. });
  20581. Object.defineProperty(Camera.prototype, "rightCamera", {
  20582. get: function () {
  20583. if (this._rigCameras.length < 2) {
  20584. return null;
  20585. }
  20586. return this._rigCameras[1];
  20587. },
  20588. enumerable: true,
  20589. configurable: true
  20590. });
  20591. Camera.prototype.getLeftTarget = function () {
  20592. if (this._rigCameras.length < 1) {
  20593. return null;
  20594. }
  20595. return this._rigCameras[0].getTarget();
  20596. };
  20597. Camera.prototype.getRightTarget = function () {
  20598. if (this._rigCameras.length < 2) {
  20599. return null;
  20600. }
  20601. return this._rigCameras[1].getTarget();
  20602. };
  20603. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20604. if (this.cameraRigMode === mode) {
  20605. return;
  20606. }
  20607. while (this._rigCameras.length > 0) {
  20608. var camera = this._rigCameras.pop();
  20609. if (camera) {
  20610. camera.dispose();
  20611. }
  20612. }
  20613. this.cameraRigMode = mode;
  20614. this._cameraRigParams = {};
  20615. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20616. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20617. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20618. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20619. // create the rig cameras, unless none
  20620. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20621. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20622. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20623. if (leftCamera && rightCamera) {
  20624. this._rigCameras.push(leftCamera);
  20625. this._rigCameras.push(rightCamera);
  20626. }
  20627. }
  20628. switch (this.cameraRigMode) {
  20629. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20630. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20631. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20632. break;
  20633. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20634. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20635. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20636. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20637. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20638. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20639. break;
  20640. case Camera.RIG_MODE_VR:
  20641. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20642. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20643. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20644. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20645. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20646. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20647. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20648. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20649. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20650. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20651. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20652. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20653. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20654. if (metrics.compensateDistortion) {
  20655. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20656. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20657. }
  20658. break;
  20659. case Camera.RIG_MODE_WEBVR:
  20660. if (rigParams.vrDisplay) {
  20661. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20662. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20663. //Left eye
  20664. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20665. this._rigCameras[0].setCameraRigParameter("left", true);
  20666. //leaving this for future reference
  20667. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20668. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20669. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20670. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20671. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20672. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20673. this._rigCameras[0].parent = this;
  20674. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20675. //Right eye
  20676. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20677. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20678. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20679. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20680. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20681. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20682. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20683. this._rigCameras[1].parent = this;
  20684. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20685. if (Camera.UseAlternateWebVRRendering) {
  20686. this._rigCameras[1]._skipRendering = true;
  20687. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20688. }
  20689. }
  20690. break;
  20691. }
  20692. this._cascadePostProcessesToRigCams();
  20693. this.update();
  20694. };
  20695. Camera.prototype._getVRProjectionMatrix = function () {
  20696. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20697. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20698. return this._projectionMatrix;
  20699. };
  20700. Camera.prototype._updateCameraRotationMatrix = function () {
  20701. //Here for WebVR
  20702. };
  20703. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20704. //Here for WebVR
  20705. };
  20706. /**
  20707. * This function MUST be overwritten by the different WebVR cameras available.
  20708. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20709. */
  20710. Camera.prototype._getWebVRProjectionMatrix = function () {
  20711. return BABYLON.Matrix.Identity();
  20712. };
  20713. /**
  20714. * This function MUST be overwritten by the different WebVR cameras available.
  20715. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20716. */
  20717. Camera.prototype._getWebVRViewMatrix = function () {
  20718. return BABYLON.Matrix.Identity();
  20719. };
  20720. Camera.prototype.setCameraRigParameter = function (name, value) {
  20721. if (!this._cameraRigParams) {
  20722. this._cameraRigParams = {};
  20723. }
  20724. this._cameraRigParams[name] = value;
  20725. //provisionnally:
  20726. if (name === "interaxialDistance") {
  20727. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20728. }
  20729. };
  20730. /**
  20731. * needs to be overridden by children so sub has required properties to be copied
  20732. */
  20733. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20734. return null;
  20735. };
  20736. /**
  20737. * May need to be overridden by children
  20738. */
  20739. Camera.prototype._updateRigCameras = function () {
  20740. for (var i = 0; i < this._rigCameras.length; i++) {
  20741. this._rigCameras[i].minZ = this.minZ;
  20742. this._rigCameras[i].maxZ = this.maxZ;
  20743. this._rigCameras[i].fov = this.fov;
  20744. }
  20745. // only update viewport when ANAGLYPH
  20746. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20747. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20748. }
  20749. };
  20750. Camera.prototype._setupInputs = function () {
  20751. };
  20752. Camera.prototype.serialize = function () {
  20753. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20754. // Type
  20755. serializationObject.type = this.getClassName();
  20756. // Parent
  20757. if (this.parent) {
  20758. serializationObject.parentId = this.parent.id;
  20759. }
  20760. if (this.inputs) {
  20761. this.inputs.serialize(serializationObject);
  20762. }
  20763. // Animations
  20764. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20765. serializationObject.ranges = this.serializeAnimationRanges();
  20766. return serializationObject;
  20767. };
  20768. Camera.prototype.clone = function (name) {
  20769. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20770. };
  20771. Camera.prototype.getDirection = function (localAxis) {
  20772. var result = BABYLON.Vector3.Zero();
  20773. this.getDirectionToRef(localAxis, result);
  20774. return result;
  20775. };
  20776. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20777. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20778. };
  20779. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20780. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20781. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20782. switch (type) {
  20783. case "ArcRotateCamera":
  20784. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20785. case "DeviceOrientationCamera":
  20786. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20787. case "FollowCamera":
  20788. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20789. case "ArcFollowCamera":
  20790. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20791. case "GamepadCamera":
  20792. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20793. case "TouchCamera":
  20794. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20795. case "VirtualJoysticksCamera":
  20796. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20797. case "WebVRFreeCamera":
  20798. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20799. case "WebVRGamepadCamera":
  20800. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20801. case "VRDeviceOrientationFreeCamera":
  20802. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20803. case "VRDeviceOrientationGamepadCamera":
  20804. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20805. case "AnaglyphArcRotateCamera":
  20806. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20807. case "AnaglyphFreeCamera":
  20808. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20809. case "AnaglyphGamepadCamera":
  20810. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20811. case "AnaglyphUniversalCamera":
  20812. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20813. case "StereoscopicArcRotateCamera":
  20814. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20815. case "StereoscopicFreeCamera":
  20816. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20817. case "StereoscopicGamepadCamera":
  20818. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20819. case "StereoscopicUniversalCamera":
  20820. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20821. case "FreeCamera":// Forcing Universal here
  20822. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20823. default:// Universal Camera is the default value
  20824. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20825. }
  20826. };
  20827. Camera.prototype.computeWorldMatrix = function () {
  20828. return this.getWorldMatrix();
  20829. };
  20830. Camera.Parse = function (parsedCamera, scene) {
  20831. var type = parsedCamera.type;
  20832. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20833. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20834. // Parent
  20835. if (parsedCamera.parentId) {
  20836. camera._waitingParentId = parsedCamera.parentId;
  20837. }
  20838. //If camera has an input manager, let it parse inputs settings
  20839. if (camera.inputs) {
  20840. camera.inputs.parse(parsedCamera);
  20841. camera._setupInputs();
  20842. }
  20843. if (camera.setPosition) {
  20844. camera.position.copyFromFloats(0, 0, 0);
  20845. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20846. }
  20847. // Target
  20848. if (parsedCamera.target) {
  20849. if (camera.setTarget) {
  20850. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20851. }
  20852. }
  20853. // Apply 3d rig, when found
  20854. if (parsedCamera.cameraRigMode) {
  20855. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20856. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20857. }
  20858. // Animations
  20859. if (parsedCamera.animations) {
  20860. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20861. var parsedAnimation = parsedCamera.animations[animationIndex];
  20862. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20863. }
  20864. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20865. }
  20866. if (parsedCamera.autoAnimate) {
  20867. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20868. }
  20869. return camera;
  20870. };
  20871. // Statics
  20872. Camera._PERSPECTIVE_CAMERA = 0;
  20873. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20874. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20875. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20876. Camera._RIG_MODE_NONE = 0;
  20877. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20878. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20879. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20880. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20881. Camera._RIG_MODE_VR = 20;
  20882. Camera._RIG_MODE_WEBVR = 21;
  20883. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20884. Camera.UseAlternateWebVRRendering = false;
  20885. __decorate([
  20886. BABYLON.serializeAsVector3()
  20887. ], Camera.prototype, "position", void 0);
  20888. __decorate([
  20889. BABYLON.serializeAsVector3()
  20890. ], Camera.prototype, "upVector", void 0);
  20891. __decorate([
  20892. BABYLON.serialize()
  20893. ], Camera.prototype, "orthoLeft", void 0);
  20894. __decorate([
  20895. BABYLON.serialize()
  20896. ], Camera.prototype, "orthoRight", void 0);
  20897. __decorate([
  20898. BABYLON.serialize()
  20899. ], Camera.prototype, "orthoBottom", void 0);
  20900. __decorate([
  20901. BABYLON.serialize()
  20902. ], Camera.prototype, "orthoTop", void 0);
  20903. __decorate([
  20904. BABYLON.serialize()
  20905. ], Camera.prototype, "fov", void 0);
  20906. __decorate([
  20907. BABYLON.serialize()
  20908. ], Camera.prototype, "minZ", void 0);
  20909. __decorate([
  20910. BABYLON.serialize()
  20911. ], Camera.prototype, "maxZ", void 0);
  20912. __decorate([
  20913. BABYLON.serialize()
  20914. ], Camera.prototype, "inertia", void 0);
  20915. __decorate([
  20916. BABYLON.serialize()
  20917. ], Camera.prototype, "mode", void 0);
  20918. __decorate([
  20919. BABYLON.serialize()
  20920. ], Camera.prototype, "layerMask", void 0);
  20921. __decorate([
  20922. BABYLON.serialize()
  20923. ], Camera.prototype, "fovMode", void 0);
  20924. __decorate([
  20925. BABYLON.serialize()
  20926. ], Camera.prototype, "cameraRigMode", void 0);
  20927. __decorate([
  20928. BABYLON.serialize()
  20929. ], Camera.prototype, "interaxialDistance", void 0);
  20930. __decorate([
  20931. BABYLON.serialize()
  20932. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20933. return Camera;
  20934. }(BABYLON.Node));
  20935. BABYLON.Camera = Camera;
  20936. })(BABYLON || (BABYLON = {}));
  20937. //# sourceMappingURL=babylon.camera.js.map
  20938. "use strict";
  20939. var BABYLON;
  20940. (function (BABYLON) {
  20941. var RenderingManager = /** @class */ (function () {
  20942. function RenderingManager(scene) {
  20943. this._renderingGroups = new Array();
  20944. this._autoClearDepthStencil = {};
  20945. this._customOpaqueSortCompareFn = {};
  20946. this._customAlphaTestSortCompareFn = {};
  20947. this._customTransparentSortCompareFn = {};
  20948. this._renderinGroupInfo = null;
  20949. this._scene = scene;
  20950. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20951. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20952. }
  20953. }
  20954. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20955. if (depth === void 0) { depth = true; }
  20956. if (stencil === void 0) { stencil = true; }
  20957. if (this._depthStencilBufferAlreadyCleaned) {
  20958. return;
  20959. }
  20960. this._scene.getEngine().clear(null, false, depth, stencil);
  20961. this._depthStencilBufferAlreadyCleaned = true;
  20962. };
  20963. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20964. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20965. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20966. var info = null;
  20967. if (observable) {
  20968. if (!this._renderinGroupInfo) {
  20969. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20970. }
  20971. info = this._renderinGroupInfo;
  20972. info.scene = this._scene;
  20973. info.camera = this._scene.activeCamera;
  20974. }
  20975. // Dispatch sprites
  20976. if (renderSprites) {
  20977. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20978. var manager = this._scene.spriteManagers[index];
  20979. this.dispatchSprites(manager);
  20980. }
  20981. }
  20982. // Render
  20983. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20984. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20985. var renderingGroup = this._renderingGroups[index];
  20986. if (!renderingGroup && !observable)
  20987. continue;
  20988. var renderingGroupMask = 0;
  20989. // Fire PRECLEAR stage
  20990. if (observable && info) {
  20991. renderingGroupMask = Math.pow(2, index);
  20992. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20993. info.renderingGroupId = index;
  20994. observable.notifyObservers(info, renderingGroupMask);
  20995. }
  20996. // Clear depth/stencil if needed
  20997. if (RenderingManager.AUTOCLEAR) {
  20998. var autoClear = this._autoClearDepthStencil[index];
  20999. if (autoClear && autoClear.autoClear) {
  21000. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  21001. }
  21002. }
  21003. if (observable && info) {
  21004. // Fire PREOPAQUE stage
  21005. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21006. observable.notifyObservers(info, renderingGroupMask);
  21007. // Fire PRETRANSPARENT stage
  21008. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21009. observable.notifyObservers(info, renderingGroupMask);
  21010. }
  21011. if (renderingGroup)
  21012. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21013. // Fire POSTTRANSPARENT stage
  21014. if (observable && info) {
  21015. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21016. observable.notifyObservers(info, renderingGroupMask);
  21017. }
  21018. }
  21019. };
  21020. RenderingManager.prototype.reset = function () {
  21021. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21022. var renderingGroup = this._renderingGroups[index];
  21023. if (renderingGroup) {
  21024. renderingGroup.prepare();
  21025. }
  21026. }
  21027. };
  21028. RenderingManager.prototype.dispose = function () {
  21029. this.freeRenderingGroups();
  21030. this._renderingGroups.length = 0;
  21031. };
  21032. /**
  21033. * Clear the info related to rendering groups preventing retention points during dispose.
  21034. */
  21035. RenderingManager.prototype.freeRenderingGroups = function () {
  21036. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21037. var renderingGroup = this._renderingGroups[index];
  21038. if (renderingGroup) {
  21039. renderingGroup.dispose();
  21040. }
  21041. }
  21042. };
  21043. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21044. if (this._renderingGroups[renderingGroupId] === undefined) {
  21045. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21046. }
  21047. };
  21048. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21049. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21050. this._prepareRenderingGroup(renderingGroupId);
  21051. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21052. };
  21053. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21054. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21055. this._prepareRenderingGroup(renderingGroupId);
  21056. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21057. };
  21058. /**
  21059. * @param subMesh The submesh to dispatch
  21060. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21061. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21062. */
  21063. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21064. if (mesh === undefined) {
  21065. mesh = subMesh.getMesh();
  21066. }
  21067. var renderingGroupId = mesh.renderingGroupId || 0;
  21068. this._prepareRenderingGroup(renderingGroupId);
  21069. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21070. };
  21071. /**
  21072. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21073. * This allowed control for front to back rendering or reversly depending of the special needs.
  21074. *
  21075. * @param renderingGroupId The rendering group id corresponding to its index
  21076. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21077. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21078. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21079. */
  21080. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21081. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21082. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21083. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21084. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21085. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21086. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21087. if (this._renderingGroups[renderingGroupId]) {
  21088. var group = this._renderingGroups[renderingGroupId];
  21089. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21090. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21091. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21092. }
  21093. };
  21094. /**
  21095. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21096. *
  21097. * @param renderingGroupId The rendering group id corresponding to its index
  21098. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21099. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21100. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21101. */
  21102. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21103. if (depth === void 0) { depth = true; }
  21104. if (stencil === void 0) { stencil = true; }
  21105. this._autoClearDepthStencil[renderingGroupId] = {
  21106. autoClear: autoClearDepthStencil,
  21107. depth: depth,
  21108. stencil: stencil
  21109. };
  21110. };
  21111. /**
  21112. * The max id used for rendering groups (not included)
  21113. */
  21114. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21115. /**
  21116. * The min id used for rendering groups (included)
  21117. */
  21118. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21119. /**
  21120. * Used to globally prevent autoclearing scenes.
  21121. */
  21122. RenderingManager.AUTOCLEAR = true;
  21123. return RenderingManager;
  21124. }());
  21125. BABYLON.RenderingManager = RenderingManager;
  21126. })(BABYLON || (BABYLON = {}));
  21127. //# sourceMappingURL=babylon.renderingManager.js.map
  21128. "use strict";
  21129. var BABYLON;
  21130. (function (BABYLON) {
  21131. var RenderingGroup = /** @class */ (function () {
  21132. /**
  21133. * Creates a new rendering group.
  21134. * @param index The rendering group index
  21135. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21136. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21137. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21138. */
  21139. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21140. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21141. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21142. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21143. this.index = index;
  21144. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21145. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21146. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21147. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21148. this._particleSystems = new BABYLON.SmartArray(256);
  21149. this._spriteManagers = new BABYLON.SmartArray(256);
  21150. this._edgesRenderers = new BABYLON.SmartArray(16);
  21151. this._scene = scene;
  21152. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21153. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21154. this.transparentSortCompareFn = transparentSortCompareFn;
  21155. }
  21156. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21157. /**
  21158. * Set the opaque sort comparison function.
  21159. * If null the sub meshes will be render in the order they were created
  21160. */
  21161. set: function (value) {
  21162. this._opaqueSortCompareFn = value;
  21163. if (value) {
  21164. this._renderOpaque = this.renderOpaqueSorted;
  21165. }
  21166. else {
  21167. this._renderOpaque = RenderingGroup.renderUnsorted;
  21168. }
  21169. },
  21170. enumerable: true,
  21171. configurable: true
  21172. });
  21173. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21174. /**
  21175. * Set the alpha test sort comparison function.
  21176. * If null the sub meshes will be render in the order they were created
  21177. */
  21178. set: function (value) {
  21179. this._alphaTestSortCompareFn = value;
  21180. if (value) {
  21181. this._renderAlphaTest = this.renderAlphaTestSorted;
  21182. }
  21183. else {
  21184. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21185. }
  21186. },
  21187. enumerable: true,
  21188. configurable: true
  21189. });
  21190. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21191. /**
  21192. * Set the transparent sort comparison function.
  21193. * If null the sub meshes will be render in the order they were created
  21194. */
  21195. set: function (value) {
  21196. if (value) {
  21197. this._transparentSortCompareFn = value;
  21198. }
  21199. else {
  21200. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21201. }
  21202. this._renderTransparent = this.renderTransparentSorted;
  21203. },
  21204. enumerable: true,
  21205. configurable: true
  21206. });
  21207. /**
  21208. * Render all the sub meshes contained in the group.
  21209. * @param customRenderFunction Used to override the default render behaviour of the group.
  21210. * @returns true if rendered some submeshes.
  21211. */
  21212. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21213. if (customRenderFunction) {
  21214. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21215. return;
  21216. }
  21217. var engine = this._scene.getEngine();
  21218. // Depth only
  21219. if (this._depthOnlySubMeshes.length !== 0) {
  21220. engine.setColorWrite(false);
  21221. this._renderAlphaTest(this._depthOnlySubMeshes);
  21222. engine.setColorWrite(true);
  21223. }
  21224. // Opaque
  21225. if (this._opaqueSubMeshes.length !== 0) {
  21226. this._renderOpaque(this._opaqueSubMeshes);
  21227. }
  21228. // Alpha test
  21229. if (this._alphaTestSubMeshes.length !== 0) {
  21230. this._renderAlphaTest(this._alphaTestSubMeshes);
  21231. }
  21232. var stencilState = engine.getStencilBuffer();
  21233. engine.setStencilBuffer(false);
  21234. // Sprites
  21235. if (renderSprites) {
  21236. this._renderSprites();
  21237. }
  21238. // Particles
  21239. if (renderParticles) {
  21240. this._renderParticles(activeMeshes);
  21241. }
  21242. if (this.onBeforeTransparentRendering) {
  21243. this.onBeforeTransparentRendering();
  21244. }
  21245. // Transparent
  21246. if (this._transparentSubMeshes.length !== 0) {
  21247. this._renderTransparent(this._transparentSubMeshes);
  21248. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21249. }
  21250. // Set back stencil to false in case it changes before the edge renderer.
  21251. engine.setStencilBuffer(false);
  21252. // Edges
  21253. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21254. this._edgesRenderers.data[edgesRendererIndex].render();
  21255. }
  21256. // Restore Stencil state.
  21257. engine.setStencilBuffer(stencilState);
  21258. };
  21259. /**
  21260. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21261. * @param subMeshes The submeshes to render
  21262. */
  21263. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21264. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21265. };
  21266. /**
  21267. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21268. * @param subMeshes The submeshes to render
  21269. */
  21270. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21271. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21272. };
  21273. /**
  21274. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21275. * @param subMeshes The submeshes to render
  21276. */
  21277. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21278. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21279. };
  21280. /**
  21281. * Renders the submeshes in a specified order.
  21282. * @param subMeshes The submeshes to sort before render
  21283. * @param sortCompareFn The comparison function use to sort
  21284. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21285. * @param transparent Specifies to activate blending if true
  21286. */
  21287. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21288. var subIndex = 0;
  21289. var subMesh;
  21290. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21291. for (; subIndex < subMeshes.length; subIndex++) {
  21292. subMesh = subMeshes.data[subIndex];
  21293. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21294. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21295. }
  21296. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21297. if (sortCompareFn) {
  21298. sortedArray.sort(sortCompareFn);
  21299. }
  21300. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21301. subMesh = sortedArray[subIndex];
  21302. if (transparent) {
  21303. var material = subMesh.getMaterial();
  21304. if (material && material.needDepthPrePass) {
  21305. var engine = material.getScene().getEngine();
  21306. engine.setColorWrite(false);
  21307. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21308. subMesh.render(false);
  21309. engine.setColorWrite(true);
  21310. }
  21311. }
  21312. subMesh.render(transparent);
  21313. }
  21314. };
  21315. /**
  21316. * Renders the submeshes in the order they were dispatched (no sort applied).
  21317. * @param subMeshes The submeshes to render
  21318. */
  21319. RenderingGroup.renderUnsorted = function (subMeshes) {
  21320. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21321. var submesh = subMeshes.data[subIndex];
  21322. submesh.render(false);
  21323. }
  21324. };
  21325. /**
  21326. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21327. * are rendered back to front if in the same alpha index.
  21328. *
  21329. * @param a The first submesh
  21330. * @param b The second submesh
  21331. * @returns The result of the comparison
  21332. */
  21333. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21334. // Alpha index first
  21335. if (a._alphaIndex > b._alphaIndex) {
  21336. return 1;
  21337. }
  21338. if (a._alphaIndex < b._alphaIndex) {
  21339. return -1;
  21340. }
  21341. // Then distance to camera
  21342. return RenderingGroup.backToFrontSortCompare(a, b);
  21343. };
  21344. /**
  21345. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21346. * are rendered back to front.
  21347. *
  21348. * @param a The first submesh
  21349. * @param b The second submesh
  21350. * @returns The result of the comparison
  21351. */
  21352. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21353. // Then distance to camera
  21354. if (a._distanceToCamera < b._distanceToCamera) {
  21355. return 1;
  21356. }
  21357. if (a._distanceToCamera > b._distanceToCamera) {
  21358. return -1;
  21359. }
  21360. return 0;
  21361. };
  21362. /**
  21363. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21364. * are rendered front to back (prevent overdraw).
  21365. *
  21366. * @param a The first submesh
  21367. * @param b The second submesh
  21368. * @returns The result of the comparison
  21369. */
  21370. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21371. // Then distance to camera
  21372. if (a._distanceToCamera < b._distanceToCamera) {
  21373. return -1;
  21374. }
  21375. if (a._distanceToCamera > b._distanceToCamera) {
  21376. return 1;
  21377. }
  21378. return 0;
  21379. };
  21380. /**
  21381. * Resets the different lists of submeshes to prepare a new frame.
  21382. */
  21383. RenderingGroup.prototype.prepare = function () {
  21384. this._opaqueSubMeshes.reset();
  21385. this._transparentSubMeshes.reset();
  21386. this._alphaTestSubMeshes.reset();
  21387. this._depthOnlySubMeshes.reset();
  21388. this._particleSystems.reset();
  21389. this._spriteManagers.reset();
  21390. this._edgesRenderers.reset();
  21391. };
  21392. RenderingGroup.prototype.dispose = function () {
  21393. this._opaqueSubMeshes.dispose();
  21394. this._transparentSubMeshes.dispose();
  21395. this._alphaTestSubMeshes.dispose();
  21396. this._depthOnlySubMeshes.dispose();
  21397. this._particleSystems.dispose();
  21398. this._spriteManagers.dispose();
  21399. this._edgesRenderers.dispose();
  21400. };
  21401. /**
  21402. * Inserts the submesh in its correct queue depending on its material.
  21403. * @param subMesh The submesh to dispatch
  21404. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21405. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21406. */
  21407. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21408. // Get mesh and materials if not provided
  21409. if (mesh === undefined) {
  21410. mesh = subMesh.getMesh();
  21411. }
  21412. if (material === undefined) {
  21413. material = subMesh.getMaterial();
  21414. }
  21415. if (material === null || material === undefined) {
  21416. return;
  21417. }
  21418. if (material.needAlphaBlendingForMesh(mesh)) {
  21419. this._transparentSubMeshes.push(subMesh);
  21420. }
  21421. else if (material.needAlphaTesting()) {
  21422. if (material.needDepthPrePass) {
  21423. this._depthOnlySubMeshes.push(subMesh);
  21424. }
  21425. this._alphaTestSubMeshes.push(subMesh);
  21426. }
  21427. else {
  21428. if (material.needDepthPrePass) {
  21429. this._depthOnlySubMeshes.push(subMesh);
  21430. }
  21431. this._opaqueSubMeshes.push(subMesh); // Opaque
  21432. }
  21433. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21434. this._edgesRenderers.push(mesh._edgesRenderer);
  21435. }
  21436. };
  21437. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21438. this._spriteManagers.push(spriteManager);
  21439. };
  21440. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21441. this._particleSystems.push(particleSystem);
  21442. };
  21443. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21444. if (this._particleSystems.length === 0) {
  21445. return;
  21446. }
  21447. // Particles
  21448. var activeCamera = this._scene.activeCamera;
  21449. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21450. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21451. var particleSystem = this._particleSystems.data[particleIndex];
  21452. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21453. continue;
  21454. }
  21455. var emitter = particleSystem.emitter;
  21456. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21457. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21458. }
  21459. }
  21460. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21461. };
  21462. RenderingGroup.prototype._renderSprites = function () {
  21463. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21464. return;
  21465. }
  21466. // Sprites
  21467. var activeCamera = this._scene.activeCamera;
  21468. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21469. for (var id = 0; id < this._spriteManagers.length; id++) {
  21470. var spriteManager = this._spriteManagers.data[id];
  21471. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21472. spriteManager.render();
  21473. }
  21474. }
  21475. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21476. };
  21477. return RenderingGroup;
  21478. }());
  21479. BABYLON.RenderingGroup = RenderingGroup;
  21480. })(BABYLON || (BABYLON = {}));
  21481. //# sourceMappingURL=babylon.renderingGroup.js.map
  21482. "use strict";
  21483. var BABYLON;
  21484. (function (BABYLON) {
  21485. /** @ignore */
  21486. var ClickInfo = /** @class */ (function () {
  21487. function ClickInfo() {
  21488. this._singleClick = false;
  21489. this._doubleClick = false;
  21490. this._hasSwiped = false;
  21491. this._ignore = false;
  21492. }
  21493. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21494. get: function () {
  21495. return this._singleClick;
  21496. },
  21497. set: function (b) {
  21498. this._singleClick = b;
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21504. get: function () {
  21505. return this._doubleClick;
  21506. },
  21507. set: function (b) {
  21508. this._doubleClick = b;
  21509. },
  21510. enumerable: true,
  21511. configurable: true
  21512. });
  21513. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21514. get: function () {
  21515. return this._hasSwiped;
  21516. },
  21517. set: function (b) {
  21518. this._hasSwiped = b;
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21524. get: function () {
  21525. return this._ignore;
  21526. },
  21527. set: function (b) {
  21528. this._ignore = b;
  21529. },
  21530. enumerable: true,
  21531. configurable: true
  21532. });
  21533. return ClickInfo;
  21534. }());
  21535. /**
  21536. * This class is used by the onRenderingGroupObservable
  21537. */
  21538. var RenderingGroupInfo = /** @class */ (function () {
  21539. function RenderingGroupInfo() {
  21540. }
  21541. /**
  21542. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21543. * This stage will be fired no matter what
  21544. */
  21545. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21546. /**
  21547. * Called before opaque object are rendered.
  21548. * This stage will be fired only if there's 3D Opaque content to render
  21549. */
  21550. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21551. /**
  21552. * Called after the opaque objects are rendered and before the transparent ones
  21553. * This stage will be fired only if there's 3D transparent content to render
  21554. */
  21555. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21556. /**
  21557. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21558. * This stage will be fired no matter what
  21559. */
  21560. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21561. return RenderingGroupInfo;
  21562. }());
  21563. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21564. /**
  21565. * Represents a scene to be rendered by the engine.
  21566. * @see http://doc.babylonjs.com/features/scene
  21567. */
  21568. var Scene = /** @class */ (function () {
  21569. /**
  21570. * Creates a new Scene
  21571. * @param engine defines the engine to use to render this scene
  21572. */
  21573. function Scene(engine) {
  21574. // Members
  21575. /**
  21576. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  21577. */
  21578. this.autoClear = true;
  21579. /**
  21580. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  21581. */
  21582. this.autoClearDepthAndStencil = true;
  21583. /**
  21584. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  21585. */
  21586. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21587. /**
  21588. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  21589. */
  21590. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21591. this._forceWireframe = false;
  21592. this._forcePointsCloud = false;
  21593. /**
  21594. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  21595. */
  21596. this.forceShowBoundingBoxes = false;
  21597. /**
  21598. * Gets or sets a boolean indicating if animations are enabled
  21599. */
  21600. this.animationsEnabled = true;
  21601. /**
  21602. * Gets or sets a boolean indicating if a constant deltatime has to be used
  21603. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  21604. */
  21605. this.useConstantAnimationDeltaTime = false;
  21606. /**
  21607. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  21608. * Please note that it requires to run a ray cast through the scene on every frame
  21609. */
  21610. this.constantlyUpdateMeshUnderPointer = false;
  21611. /**
  21612. * Defines the HTML cursor to use when hovering over interactive elements
  21613. */
  21614. this.hoverCursor = "pointer";
  21615. /**
  21616. * Defines the HTML default cursor to use (empty by default)
  21617. */
  21618. this.defaultCursor = "";
  21619. /**
  21620. * This is used to call preventDefault() on pointer down
  21621. * in order to block unwanted artifacts like system double clicks
  21622. */
  21623. this.preventDefaultOnPointerDown = true;
  21624. // Metadata
  21625. /**
  21626. * Gets or sets user defined metadata
  21627. */
  21628. this.metadata = null;
  21629. /**
  21630. * Use this array to add regular expressions used to disable offline support for specific urls
  21631. */
  21632. this.disableOfflineSupportExceptionRules = new Array();
  21633. /**
  21634. * An event triggered when the scene is disposed.
  21635. */
  21636. this.onDisposeObservable = new BABYLON.Observable();
  21637. this._onDisposeObserver = null;
  21638. /**
  21639. * An event triggered before rendering the scene (right after animations and physics)
  21640. */
  21641. this.onBeforeRenderObservable = new BABYLON.Observable();
  21642. this._onBeforeRenderObserver = null;
  21643. /**
  21644. * An event triggered after rendering the scene
  21645. */
  21646. this.onAfterRenderObservable = new BABYLON.Observable();
  21647. this._onAfterRenderObserver = null;
  21648. /**
  21649. * An event triggered before animating the scene
  21650. */
  21651. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21652. /**
  21653. * An event triggered after animations processing
  21654. */
  21655. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21656. /**
  21657. * An event triggered before draw calls are ready to be sent
  21658. */
  21659. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21660. /**
  21661. * An event triggered after draw calls have been sent
  21662. */
  21663. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21664. /**
  21665. * An event triggered when physic simulation is about to be run
  21666. */
  21667. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21668. /**
  21669. * An event triggered when physic simulation has been done
  21670. */
  21671. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21672. /**
  21673. * An event triggered when the scene is ready
  21674. */
  21675. this.onReadyObservable = new BABYLON.Observable();
  21676. /**
  21677. * An event triggered before rendering a camera
  21678. */
  21679. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21680. this._onBeforeCameraRenderObserver = null;
  21681. /**
  21682. * An event triggered after rendering a camera
  21683. */
  21684. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21685. this._onAfterCameraRenderObserver = null;
  21686. /**
  21687. * An event triggered when active meshes evaluation is about to start
  21688. */
  21689. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21690. /**
  21691. * An event triggered when active meshes evaluation is done
  21692. */
  21693. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21694. /**
  21695. * An event triggered when particles rendering is about to start
  21696. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21697. */
  21698. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21699. /**
  21700. * An event triggered when particles rendering is done
  21701. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21702. */
  21703. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21704. /**
  21705. * An event triggered when sprites rendering is about to start
  21706. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21707. */
  21708. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21709. /**
  21710. * An event triggered when sprites rendering is done
  21711. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21712. */
  21713. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21714. /**
  21715. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21716. */
  21717. this.onDataLoadedObservable = new BABYLON.Observable();
  21718. /**
  21719. * An event triggered when a camera is created
  21720. */
  21721. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered when a camera is removed
  21724. */
  21725. this.onCameraRemovedObservable = new BABYLON.Observable();
  21726. /**
  21727. * An event triggered when a light is created
  21728. */
  21729. this.onNewLightAddedObservable = new BABYLON.Observable();
  21730. /**
  21731. * An event triggered when a light is removed
  21732. */
  21733. this.onLightRemovedObservable = new BABYLON.Observable();
  21734. /**
  21735. * An event triggered when a geometry is created
  21736. */
  21737. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21738. /**
  21739. * An event triggered when a geometry is removed
  21740. */
  21741. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21742. /**
  21743. * An event triggered when a transform node is created
  21744. */
  21745. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21746. /**
  21747. * An event triggered when a transform node is removed
  21748. */
  21749. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21750. /**
  21751. * An event triggered when a mesh is created
  21752. */
  21753. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21754. /**
  21755. * An event triggered when a mesh is removed
  21756. */
  21757. this.onMeshRemovedObservable = new BABYLON.Observable();
  21758. /**
  21759. * An event triggered when render targets are about to be rendered
  21760. * Can happen multiple times per frame.
  21761. */
  21762. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21763. /**
  21764. * An event triggered when render targets were rendered.
  21765. * Can happen multiple times per frame.
  21766. */
  21767. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21768. /**
  21769. * An event triggered before calculating deterministic simulation step
  21770. */
  21771. this.onBeforeStepObservable = new BABYLON.Observable();
  21772. /**
  21773. * An event triggered after calculating deterministic simulation step
  21774. */
  21775. this.onAfterStepObservable = new BABYLON.Observable();
  21776. /**
  21777. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21778. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21779. * 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)
  21780. */
  21781. this.onRenderingGroupObservable = new BABYLON.Observable();
  21782. // Animations
  21783. /**
  21784. * Gets a list of Animations associated with the scene
  21785. */
  21786. this.animations = [];
  21787. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21788. /**
  21789. * 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).
  21790. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21791. */
  21792. this.onPrePointerObservable = new BABYLON.Observable();
  21793. /**
  21794. * Observable event triggered each time an input event is received from the rendering canvas
  21795. */
  21796. this.onPointerObservable = new BABYLON.Observable();
  21797. this._meshPickProceed = false;
  21798. this._currentPickResult = null;
  21799. this._previousPickResult = null;
  21800. this._totalPointersPressed = 0;
  21801. this._doubleClickOccured = false;
  21802. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21803. this.cameraToUseForPointers = null;
  21804. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21805. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21806. this._startingPointerTime = 0;
  21807. this._previousStartingPointerTime = 0;
  21808. // Deterministic lockstep
  21809. this._timeAccumulator = 0;
  21810. this._currentStepId = 0;
  21811. this._currentInternalStep = 0;
  21812. // Keyboard
  21813. /**
  21814. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21815. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21816. */
  21817. this.onPreKeyboardObservable = new BABYLON.Observable();
  21818. /**
  21819. * Observable event triggered each time an keyboard event is received from the hosting window
  21820. */
  21821. this.onKeyboardObservable = new BABYLON.Observable();
  21822. // Coordinates system
  21823. this._useRightHandedSystem = false;
  21824. // Fog
  21825. this._fogEnabled = true;
  21826. this._fogMode = Scene.FOGMODE_NONE;
  21827. /**
  21828. * Gets or sets the fog color to use
  21829. * @see http://doc.babylonjs.com/babylon101/environment#fog
  21830. */
  21831. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21832. /**
  21833. * Gets or sets the fog density to use
  21834. * @see http://doc.babylonjs.com/babylon101/environment#fog
  21835. */
  21836. this.fogDensity = 0.1;
  21837. /**
  21838. * Gets or sets the fog start distance to use
  21839. * @see http://doc.babylonjs.com/babylon101/environment#fog
  21840. */
  21841. this.fogStart = 0;
  21842. /**
  21843. * Gets or sets the fog end distance to use
  21844. * @see http://doc.babylonjs.com/babylon101/environment#fog
  21845. */
  21846. this.fogEnd = 1000.0;
  21847. // Lights
  21848. this._shadowsEnabled = true;
  21849. this._lightsEnabled = true;
  21850. /**
  21851. * All of the lights added to this scene
  21852. * @see http://doc.babylonjs.com/babylon101/lights
  21853. */
  21854. this.lights = new Array();
  21855. // Cameras
  21856. /** All of the cameras added to this scene.
  21857. * @see http://doc.babylonjs.com/babylon101/cameras
  21858. */
  21859. this.cameras = new Array();
  21860. /** All of the active cameras added to this scene. */
  21861. this.activeCameras = new Array();
  21862. // Meshes
  21863. /**
  21864. * All of the tranform nodes added to this scene
  21865. * @see http://doc.babylonjs.com/how_to/transformnode
  21866. */
  21867. this.transformNodes = new Array();
  21868. /**
  21869. * All of the (abstract) meshes added to this scene
  21870. */
  21871. this.meshes = new Array();
  21872. /**
  21873. * All of the animation groups added to this scene
  21874. * @see http://doc.babylonjs.com/how_to/group
  21875. */
  21876. this.animationGroups = new Array();
  21877. // Geometries
  21878. this._geometries = new Array();
  21879. /**
  21880. * All of the materials added to this scene
  21881. * @see http://doc.babylonjs.com/babylon101/materials
  21882. */
  21883. this.materials = new Array();
  21884. /**
  21885. * All of the multi-materials added to this scene
  21886. * @see http://doc.babylonjs.com/how_to/multi_materials
  21887. */
  21888. this.multiMaterials = new Array();
  21889. // Textures
  21890. this._texturesEnabled = true;
  21891. /**
  21892. * All of the textures added to this scene
  21893. */
  21894. this.textures = new Array();
  21895. // Particles
  21896. /**
  21897. * Gets or sets a boolean indicating if particles are enabled on this scene
  21898. */
  21899. this.particlesEnabled = true;
  21900. /**
  21901. * All of the particle systems added to this scene
  21902. * @see http://doc.babylonjs.com/babylon101/particles
  21903. */
  21904. this.particleSystems = new Array();
  21905. // Sprites
  21906. /**
  21907. * Gets or sets a boolean indicating if sprites are enabled on this scene
  21908. */
  21909. this.spritesEnabled = true;
  21910. /**
  21911. * All of the sprite managers added to this scene
  21912. * @see http://doc.babylonjs.com/babylon101/sprites
  21913. */
  21914. this.spriteManagers = new Array();
  21915. /**
  21916. * The list of layers (background and foreground) of the scene
  21917. */
  21918. this.layers = new Array();
  21919. /**
  21920. * The list of effect layers (highlights/glow) added to the scene
  21921. * @see http://doc.babylonjs.com/how_to/highlight_layer
  21922. * @see http://doc.babylonjs.com/how_to/glow_layer
  21923. */
  21924. this.effectLayers = new Array();
  21925. // Skeletons
  21926. this._skeletonsEnabled = true;
  21927. /**
  21928. * The list of skeletons added to the scene
  21929. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21930. */
  21931. this.skeletons = new Array();
  21932. // Morph targets
  21933. /**
  21934. * The list of morph target managers added to the scene
  21935. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  21936. */
  21937. this.morphTargetManagers = new Array();
  21938. // Lens flares
  21939. /**
  21940. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  21941. */
  21942. this.lensFlaresEnabled = true;
  21943. /**
  21944. * The list of lens flare system added to the scene
  21945. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  21946. */
  21947. this.lensFlareSystems = new Array();
  21948. // Collisions
  21949. /**
  21950. * Gets or sets a boolean indicating if collisions are enabled on this scene
  21951. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21952. */
  21953. this.collisionsEnabled = true;
  21954. /**
  21955. * Defines the gravity applied to this scene (used only for collisions)
  21956. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21957. */
  21958. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21959. // Postprocesses
  21960. /**
  21961. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  21962. */
  21963. this.postProcessesEnabled = true;
  21964. /**
  21965. * The list of postprocesses added to the scene
  21966. */
  21967. this.postProcesses = new Array();
  21968. // Customs render targets
  21969. /**
  21970. * Gets or sets a boolean indicating if render targets are enabled on this scene
  21971. */
  21972. this.renderTargetsEnabled = true;
  21973. /**
  21974. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  21975. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  21976. */
  21977. this.dumpNextRenderTargets = false;
  21978. /**
  21979. * The list of user defined render targets added to the scene
  21980. */
  21981. this.customRenderTargets = new Array();
  21982. /**
  21983. * Gets the list of meshes imported to the scene through SceneLoader
  21984. */
  21985. this.importedMeshesFiles = new Array();
  21986. // Probes
  21987. /**
  21988. * Gets or sets a boolean indicating if probes are enabled on this scene
  21989. */
  21990. this.probesEnabled = true;
  21991. /**
  21992. * The list of reflection probes added to the scene
  21993. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  21994. */
  21995. this.reflectionProbes = new Array();
  21996. /** @ignore */
  21997. this._actionManagers = new Array();
  21998. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21999. // Procedural textures
  22000. /**
  22001. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  22002. */
  22003. this.proceduralTexturesEnabled = true;
  22004. /**
  22005. * The list of procedural textures added to the scene
  22006. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  22007. */
  22008. this.proceduralTextures = new Array();
  22009. /**
  22010. * The list of sound tracks added to the scene
  22011. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  22012. */
  22013. this.soundTracks = new Array();
  22014. this._audioEnabled = true;
  22015. this._headphone = false;
  22016. // Performance counters
  22017. this._totalVertices = new BABYLON.PerfCounter();
  22018. /** @ignore */
  22019. this._activeIndices = new BABYLON.PerfCounter();
  22020. /** @ignore */
  22021. this._activeParticles = new BABYLON.PerfCounter();
  22022. /** @ignore */
  22023. this._activeBones = new BABYLON.PerfCounter();
  22024. this._animationTime = 0;
  22025. /**
  22026. * Gets or sets a general scale for animation speed
  22027. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  22028. */
  22029. this.animationTimeScale = 1;
  22030. this._renderId = 0;
  22031. this._executeWhenReadyTimeoutId = -1;
  22032. this._intermediateRendering = false;
  22033. this._viewUpdateFlag = -1;
  22034. this._projectionUpdateFlag = -1;
  22035. this._alternateViewUpdateFlag = -1;
  22036. this._alternateProjectionUpdateFlag = -1;
  22037. /** @ignore */
  22038. this._toBeDisposed = new BABYLON.SmartArray(256);
  22039. this._activeRequests = new Array();
  22040. this._pendingData = new Array();
  22041. this._isDisposed = false;
  22042. /**
  22043. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  22044. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  22045. */
  22046. this.dispatchAllSubMeshesOfActiveMeshes = false;
  22047. this._activeMeshes = new BABYLON.SmartArray(256);
  22048. this._processedMaterials = new BABYLON.SmartArray(256);
  22049. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  22050. /** @ignore */
  22051. this._activeParticleSystems = new BABYLON.SmartArray(256);
  22052. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  22053. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  22054. /** @ignore */
  22055. this._activeAnimatables = new Array();
  22056. this._transformMatrix = BABYLON.Matrix.Zero();
  22057. this._useAlternateCameraConfiguration = false;
  22058. this._alternateRendering = false;
  22059. /**
  22060. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  22061. * This is useful if there are more lights that the maximum simulteanous authorized
  22062. */
  22063. this.requireLightSorting = false;
  22064. this._depthRenderer = {};
  22065. this._activeMeshesFrozen = false;
  22066. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  22067. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  22068. this._engine.scenes.push(this);
  22069. this._uid = null;
  22070. this._renderingManager = new BABYLON.RenderingManager(this);
  22071. this.postProcessManager = new BABYLON.PostProcessManager(this);
  22072. if (BABYLON.OutlineRenderer) {
  22073. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  22074. }
  22075. if (BABYLON.Tools.IsWindowObjectExist()) {
  22076. this.attachControl();
  22077. }
  22078. //simplification queue
  22079. if (BABYLON.SimplificationQueue) {
  22080. this.simplificationQueue = new BABYLON.SimplificationQueue();
  22081. }
  22082. //collision coordinator initialization. For now legacy per default.
  22083. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  22084. // Uniform Buffer
  22085. this._createUbo();
  22086. // Default Image processing definition.
  22087. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  22088. }
  22089. Object.defineProperty(Scene, "FOGMODE_NONE", {
  22090. /** The fog is deactivated */
  22091. get: function () {
  22092. return Scene._FOGMODE_NONE;
  22093. },
  22094. enumerable: true,
  22095. configurable: true
  22096. });
  22097. Object.defineProperty(Scene, "FOGMODE_EXP", {
  22098. /** The fog density is following an exponential function */
  22099. get: function () {
  22100. return Scene._FOGMODE_EXP;
  22101. },
  22102. enumerable: true,
  22103. configurable: true
  22104. });
  22105. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  22106. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  22107. get: function () {
  22108. return Scene._FOGMODE_EXP2;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  22114. /** The fog density is following a linear function. */
  22115. get: function () {
  22116. return Scene._FOGMODE_LINEAR;
  22117. },
  22118. enumerable: true,
  22119. configurable: true
  22120. });
  22121. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22122. /**
  22123. * Texture used in all pbr material as the reflection texture.
  22124. * As in the majority of the scene they are the same (exception for multi room and so on),
  22125. * this is easier to reference from here than from all the materials.
  22126. */
  22127. get: function () {
  22128. return this._environmentTexture;
  22129. },
  22130. /**
  22131. * Texture used in all pbr material as the reflection texture.
  22132. * As in the majority of the scene they are the same (exception for multi room and so on),
  22133. * this is easier to set here than in all the materials.
  22134. */
  22135. set: function (value) {
  22136. if (this._environmentTexture === value) {
  22137. return;
  22138. }
  22139. this._environmentTexture = value;
  22140. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22141. },
  22142. enumerable: true,
  22143. configurable: true
  22144. });
  22145. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22146. /**
  22147. * Default image processing configuration used either in the rendering
  22148. * Forward main pass or through the imageProcessingPostProcess if present.
  22149. * As in the majority of the scene they are the same (exception for multi camera),
  22150. * this is easier to reference from here than from all the materials and post process.
  22151. *
  22152. * No setter as we it is a shared configuration, you can set the values instead.
  22153. */
  22154. get: function () {
  22155. return this._imageProcessingConfiguration;
  22156. },
  22157. enumerable: true,
  22158. configurable: true
  22159. });
  22160. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22161. get: function () {
  22162. return this._forceWireframe;
  22163. },
  22164. /**
  22165. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  22166. */
  22167. set: function (value) {
  22168. if (this._forceWireframe === value) {
  22169. return;
  22170. }
  22171. this._forceWireframe = value;
  22172. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22178. get: function () {
  22179. return this._forcePointsCloud;
  22180. },
  22181. /**
  22182. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  22183. */
  22184. set: function (value) {
  22185. if (this._forcePointsCloud === value) {
  22186. return;
  22187. }
  22188. this._forcePointsCloud = value;
  22189. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22190. },
  22191. enumerable: true,
  22192. configurable: true
  22193. });
  22194. Object.defineProperty(Scene.prototype, "onDispose", {
  22195. /** Sets a function to be executed when this scene is disposed. */
  22196. set: function (callback) {
  22197. if (this._onDisposeObserver) {
  22198. this.onDisposeObservable.remove(this._onDisposeObserver);
  22199. }
  22200. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22201. },
  22202. enumerable: true,
  22203. configurable: true
  22204. });
  22205. Object.defineProperty(Scene.prototype, "beforeRender", {
  22206. /** Sets a function to be executed before rendering this scene */
  22207. set: function (callback) {
  22208. if (this._onBeforeRenderObserver) {
  22209. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22210. }
  22211. if (callback) {
  22212. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22213. }
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. Object.defineProperty(Scene.prototype, "afterRender", {
  22219. /** Sets a function to be executed after rendering this scene */
  22220. set: function (callback) {
  22221. if (this._onAfterRenderObserver) {
  22222. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22223. }
  22224. if (callback) {
  22225. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22226. }
  22227. },
  22228. enumerable: true,
  22229. configurable: true
  22230. });
  22231. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22232. /** Sets a function to be executed before rendering a camera*/
  22233. set: function (callback) {
  22234. if (this._onBeforeCameraRenderObserver) {
  22235. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22236. }
  22237. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22238. },
  22239. enumerable: true,
  22240. configurable: true
  22241. });
  22242. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22243. /** Sets a function to be executed after rendering a camera*/
  22244. set: function (callback) {
  22245. if (this._onAfterCameraRenderObserver) {
  22246. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22247. }
  22248. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22249. },
  22250. enumerable: true,
  22251. configurable: true
  22252. });
  22253. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22254. /**
  22255. * Gets the gamepad manager associated with the scene
  22256. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  22257. */
  22258. get: function () {
  22259. if (!this._gamepadManager) {
  22260. this._gamepadManager = new BABYLON.GamepadManager(this);
  22261. }
  22262. return this._gamepadManager;
  22263. },
  22264. enumerable: true,
  22265. configurable: true
  22266. });
  22267. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22268. /**
  22269. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  22270. */
  22271. get: function () {
  22272. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22278. get: function () {
  22279. return this._useRightHandedSystem;
  22280. },
  22281. /**
  22282. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  22283. */
  22284. set: function (value) {
  22285. if (this._useRightHandedSystem === value) {
  22286. return;
  22287. }
  22288. this._useRightHandedSystem = value;
  22289. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22290. },
  22291. enumerable: true,
  22292. configurable: true
  22293. });
  22294. /**
  22295. * Sets the step Id used by deterministic lock step
  22296. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  22297. * @param newStepId defines the step Id
  22298. */
  22299. Scene.prototype.setStepId = function (newStepId) {
  22300. this._currentStepId = newStepId;
  22301. };
  22302. ;
  22303. /**
  22304. * Gets the step Id used by deterministic lock step
  22305. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  22306. * @returns the step Id
  22307. */
  22308. Scene.prototype.getStepId = function () {
  22309. return this._currentStepId;
  22310. };
  22311. ;
  22312. /**
  22313. * Gets the internal step used by deterministic lock step
  22314. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  22315. * @returns the internal step
  22316. */
  22317. Scene.prototype.getInternalStep = function () {
  22318. return this._currentInternalStep;
  22319. };
  22320. ;
  22321. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22322. get: function () {
  22323. return this._fogEnabled;
  22324. },
  22325. /**
  22326. * Gets or sets a boolean indicating if fog is enabled on this scene
  22327. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22328. */
  22329. set: function (value) {
  22330. if (this._fogEnabled === value) {
  22331. return;
  22332. }
  22333. this._fogEnabled = value;
  22334. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. Object.defineProperty(Scene.prototype, "fogMode", {
  22340. get: function () {
  22341. return this._fogMode;
  22342. },
  22343. /**
  22344. * Gets or sets the fog mode to use
  22345. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22346. */
  22347. set: function (value) {
  22348. if (this._fogMode === value) {
  22349. return;
  22350. }
  22351. this._fogMode = value;
  22352. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22353. },
  22354. enumerable: true,
  22355. configurable: true
  22356. });
  22357. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22358. get: function () {
  22359. return this._shadowsEnabled;
  22360. },
  22361. /**
  22362. * Gets or sets a boolean indicating if shadows are enabled on this scene
  22363. */
  22364. set: function (value) {
  22365. if (this._shadowsEnabled === value) {
  22366. return;
  22367. }
  22368. this._shadowsEnabled = value;
  22369. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22370. },
  22371. enumerable: true,
  22372. configurable: true
  22373. });
  22374. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22375. get: function () {
  22376. return this._lightsEnabled;
  22377. },
  22378. /**
  22379. * Gets or sets a boolean indicating if lights are enabled on this scene
  22380. */
  22381. set: function (value) {
  22382. if (this._lightsEnabled === value) {
  22383. return;
  22384. }
  22385. this._lightsEnabled = value;
  22386. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22387. },
  22388. enumerable: true,
  22389. configurable: true
  22390. });
  22391. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22392. /** The default material used on meshes when no material is affected */
  22393. get: function () {
  22394. if (!this._defaultMaterial) {
  22395. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22396. }
  22397. return this._defaultMaterial;
  22398. },
  22399. /** The default material used on meshes when no material is affected */
  22400. set: function (value) {
  22401. this._defaultMaterial = value;
  22402. },
  22403. enumerable: true,
  22404. configurable: true
  22405. });
  22406. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22407. get: function () {
  22408. return this._texturesEnabled;
  22409. },
  22410. /**
  22411. * Gets or sets a boolean indicating if textures are enabled on this scene
  22412. */
  22413. set: function (value) {
  22414. if (this._texturesEnabled === value) {
  22415. return;
  22416. }
  22417. this._texturesEnabled = value;
  22418. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22424. get: function () {
  22425. return this._skeletonsEnabled;
  22426. },
  22427. /**
  22428. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  22429. */
  22430. set: function (value) {
  22431. if (this._skeletonsEnabled === value) {
  22432. return;
  22433. }
  22434. this._skeletonsEnabled = value;
  22435. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22436. },
  22437. enumerable: true,
  22438. configurable: true
  22439. });
  22440. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22441. /**
  22442. * Gets the postprocess render pipeline manager
  22443. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  22444. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  22445. */
  22446. get: function () {
  22447. if (!this._postProcessRenderPipelineManager) {
  22448. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22449. }
  22450. return this._postProcessRenderPipelineManager;
  22451. },
  22452. enumerable: true,
  22453. configurable: true
  22454. });
  22455. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22456. /**
  22457. * Gets the main soundtrack associated with the scene
  22458. */
  22459. get: function () {
  22460. if (!this._mainSoundTrack) {
  22461. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22462. }
  22463. return this._mainSoundTrack;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22469. /** @ignore */
  22470. get: function () {
  22471. return this._alternateRendering;
  22472. },
  22473. enumerable: true,
  22474. configurable: true
  22475. });
  22476. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22477. /**
  22478. * Gets the list of frustum planes (built from the active camera)
  22479. */
  22480. get: function () {
  22481. return this._frustumPlanes;
  22482. },
  22483. enumerable: true,
  22484. configurable: true
  22485. });
  22486. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22487. /**
  22488. * Gets the current geometry buffer associated to the scene.
  22489. */
  22490. get: function () {
  22491. return this._geometryBufferRenderer;
  22492. },
  22493. /**
  22494. * Sets the current geometry buffer for the scene.
  22495. */
  22496. set: function (geometryBufferRenderer) {
  22497. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22498. this._geometryBufferRenderer = geometryBufferRenderer;
  22499. }
  22500. },
  22501. enumerable: true,
  22502. configurable: true
  22503. });
  22504. Object.defineProperty(Scene.prototype, "debugLayer", {
  22505. /**
  22506. * Gets the debug layer associated with the scene
  22507. * @see http://doc.babylonjs.com/features/playground_debuglayer
  22508. */
  22509. get: function () {
  22510. if (!this._debugLayer) {
  22511. this._debugLayer = new BABYLON.DebugLayer(this);
  22512. }
  22513. return this._debugLayer;
  22514. },
  22515. enumerable: true,
  22516. configurable: true
  22517. });
  22518. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22519. /**
  22520. * Gets a boolean indicating if collisions are processed on a web worker
  22521. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  22522. */
  22523. get: function () {
  22524. return this._workerCollisions;
  22525. },
  22526. set: function (enabled) {
  22527. if (!BABYLON.CollisionCoordinatorLegacy) {
  22528. return;
  22529. }
  22530. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22531. this._workerCollisions = enabled;
  22532. if (this.collisionCoordinator) {
  22533. this.collisionCoordinator.destroy();
  22534. }
  22535. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22536. this.collisionCoordinator.init(this);
  22537. },
  22538. enumerable: true,
  22539. configurable: true
  22540. });
  22541. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22542. /**
  22543. * Gets the octree used to boost mesh selection (picking)
  22544. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  22545. */
  22546. get: function () {
  22547. return this._selectionOctree;
  22548. },
  22549. enumerable: true,
  22550. configurable: true
  22551. });
  22552. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22553. /**
  22554. * Gets the mesh that is currently under the pointer
  22555. */
  22556. get: function () {
  22557. return this._pointerOverMesh;
  22558. },
  22559. enumerable: true,
  22560. configurable: true
  22561. });
  22562. Object.defineProperty(Scene.prototype, "pointerX", {
  22563. /**
  22564. * Gets the current on-screen X position of the pointer
  22565. */
  22566. get: function () {
  22567. return this._pointerX;
  22568. },
  22569. enumerable: true,
  22570. configurable: true
  22571. });
  22572. Object.defineProperty(Scene.prototype, "pointerY", {
  22573. /**
  22574. * Gets the current on-screen Y position of the pointer
  22575. */
  22576. get: function () {
  22577. return this._pointerY;
  22578. },
  22579. enumerable: true,
  22580. configurable: true
  22581. });
  22582. /**
  22583. * Gets the cached material (ie. the latest rendered one)
  22584. * @returns the cached material
  22585. */
  22586. Scene.prototype.getCachedMaterial = function () {
  22587. return this._cachedMaterial;
  22588. };
  22589. /**
  22590. * Gets the cached effect (ie. the latest rendered one)
  22591. * @returns the cached effect
  22592. */
  22593. Scene.prototype.getCachedEffect = function () {
  22594. return this._cachedEffect;
  22595. };
  22596. /**
  22597. * Gets the cached visibility state (ie. the latest rendered one)
  22598. * @returns the cached visibility state
  22599. */
  22600. Scene.prototype.getCachedVisibility = function () {
  22601. return this._cachedVisibility;
  22602. };
  22603. /**
  22604. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  22605. * @param material defines the current material
  22606. * @param effect defines the current effect
  22607. * @param visibility defines the current visibility state
  22608. * @returns true if one parameter is not cached
  22609. */
  22610. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22611. if (visibility === void 0) { visibility = 1; }
  22612. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22613. };
  22614. /**
  22615. * Gets the bounding box renderer associated with the scene
  22616. * @returns a BoundingBoxRenderer
  22617. */
  22618. Scene.prototype.getBoundingBoxRenderer = function () {
  22619. if (!this._boundingBoxRenderer) {
  22620. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22621. }
  22622. return this._boundingBoxRenderer;
  22623. };
  22624. /**
  22625. * Gets the outline renderer associated with the scene
  22626. * @returns a OutlineRenderer
  22627. */
  22628. Scene.prototype.getOutlineRenderer = function () {
  22629. return this._outlineRenderer;
  22630. };
  22631. /**
  22632. * Gets the engine associated with the scene
  22633. * @returns an Engine
  22634. */
  22635. Scene.prototype.getEngine = function () {
  22636. return this._engine;
  22637. };
  22638. /**
  22639. * Gets the total number of vertices rendered per frame
  22640. * @returns the total number of vertices rendered per frame
  22641. */
  22642. Scene.prototype.getTotalVertices = function () {
  22643. return this._totalVertices.current;
  22644. };
  22645. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22646. /**
  22647. * Gets the performance counter for total vertices
  22648. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  22649. */
  22650. get: function () {
  22651. return this._totalVertices;
  22652. },
  22653. enumerable: true,
  22654. configurable: true
  22655. });
  22656. /**
  22657. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  22658. * @returns the total number of active indices rendered per frame
  22659. */
  22660. Scene.prototype.getActiveIndices = function () {
  22661. return this._activeIndices.current;
  22662. };
  22663. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22664. /**
  22665. * Gets the performance counter for active indices
  22666. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  22667. */
  22668. get: function () {
  22669. return this._activeIndices;
  22670. },
  22671. enumerable: true,
  22672. configurable: true
  22673. });
  22674. /**
  22675. * Gets the total number of active particles rendered per frame
  22676. * @returns the total number of active particles rendered per frame
  22677. */
  22678. Scene.prototype.getActiveParticles = function () {
  22679. return this._activeParticles.current;
  22680. };
  22681. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22682. /**
  22683. * Gets the performance counter for active particles
  22684. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  22685. */
  22686. get: function () {
  22687. return this._activeParticles;
  22688. },
  22689. enumerable: true,
  22690. configurable: true
  22691. });
  22692. /**
  22693. * Gets the total number of active bones rendered per frame
  22694. * @returns the total number of active bones rendered per frame
  22695. */
  22696. Scene.prototype.getActiveBones = function () {
  22697. return this._activeBones.current;
  22698. };
  22699. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22700. /**
  22701. * Gets the performance counter for active bones
  22702. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  22703. */
  22704. get: function () {
  22705. return this._activeBones;
  22706. },
  22707. enumerable: true,
  22708. configurable: true
  22709. });
  22710. /** @ignore */
  22711. Scene.prototype.getInterFramePerfCounter = function () {
  22712. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22713. return 0;
  22714. };
  22715. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22716. /** @ignore */
  22717. get: function () {
  22718. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22719. return null;
  22720. },
  22721. enumerable: true,
  22722. configurable: true
  22723. });
  22724. /** @ignore */
  22725. Scene.prototype.getLastFrameDuration = function () {
  22726. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22727. return 0;
  22728. };
  22729. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22730. /** @ignore */
  22731. get: function () {
  22732. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22733. return null;
  22734. },
  22735. enumerable: true,
  22736. configurable: true
  22737. });
  22738. /** @ignore */
  22739. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22740. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22741. return 0;
  22742. };
  22743. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22744. /** @ignore */
  22745. get: function () {
  22746. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22747. return null;
  22748. },
  22749. enumerable: true,
  22750. configurable: true
  22751. });
  22752. /**
  22753. * Gets the array of active meshes
  22754. * @returns an array of AbstractMesh
  22755. */
  22756. Scene.prototype.getActiveMeshes = function () {
  22757. return this._activeMeshes;
  22758. };
  22759. /** @ignore */
  22760. Scene.prototype.getRenderTargetsDuration = function () {
  22761. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22762. return 0;
  22763. };
  22764. /** @ignore */
  22765. Scene.prototype.getRenderDuration = function () {
  22766. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22767. return 0;
  22768. };
  22769. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22770. /** @ignore */
  22771. get: function () {
  22772. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22773. return null;
  22774. },
  22775. enumerable: true,
  22776. configurable: true
  22777. });
  22778. /** @ignore */
  22779. Scene.prototype.getParticlesDuration = function () {
  22780. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22781. return 0;
  22782. };
  22783. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22784. /** @ignore */
  22785. get: function () {
  22786. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22787. return null;
  22788. },
  22789. enumerable: true,
  22790. configurable: true
  22791. });
  22792. /** @ignore */
  22793. Scene.prototype.getSpritesDuration = function () {
  22794. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22795. return 0;
  22796. };
  22797. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22798. /** @ignore */
  22799. get: function () {
  22800. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22801. return null;
  22802. },
  22803. enumerable: true,
  22804. configurable: true
  22805. });
  22806. /**
  22807. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  22808. * @returns a number
  22809. */
  22810. Scene.prototype.getAnimationRatio = function () {
  22811. return this._animationRatio;
  22812. };
  22813. /**
  22814. * Gets an unique Id for the current frame
  22815. * @returns a number
  22816. */
  22817. Scene.prototype.getRenderId = function () {
  22818. return this._renderId;
  22819. };
  22820. /** Call this function if you want to manually increment the render Id*/
  22821. Scene.prototype.incrementRenderId = function () {
  22822. this._renderId++;
  22823. };
  22824. Scene.prototype._updatePointerPosition = function (evt) {
  22825. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22826. if (!canvasRect) {
  22827. return;
  22828. }
  22829. this._pointerX = evt.clientX - canvasRect.left;
  22830. this._pointerY = evt.clientY - canvasRect.top;
  22831. this._unTranslatedPointerX = this._pointerX;
  22832. this._unTranslatedPointerY = this._pointerY;
  22833. };
  22834. Scene.prototype._createUbo = function () {
  22835. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22836. this._sceneUbo.addUniform("viewProjection", 16);
  22837. this._sceneUbo.addUniform("view", 16);
  22838. };
  22839. Scene.prototype._createAlternateUbo = function () {
  22840. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22841. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22842. this._alternateSceneUbo.addUniform("view", 16);
  22843. };
  22844. // Pointers handling
  22845. /**
  22846. * Use this method to simulate a pointer move on a mesh
  22847. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22848. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22849. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22850. * @returns the current scene
  22851. */
  22852. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22853. var evt = new PointerEvent("pointermove", pointerEventInit);
  22854. return this._processPointerMove(pickResult, evt);
  22855. };
  22856. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22857. var canvas = this._engine.getRenderingCanvas();
  22858. if (!canvas) {
  22859. return this;
  22860. }
  22861. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22862. this.setPointerOverSprite(null);
  22863. this.setPointerOverMesh(pickResult.pickedMesh);
  22864. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22865. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22866. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22867. }
  22868. else {
  22869. canvas.style.cursor = this.hoverCursor;
  22870. }
  22871. }
  22872. else {
  22873. canvas.style.cursor = this.defaultCursor;
  22874. }
  22875. }
  22876. else {
  22877. this.setPointerOverMesh(null);
  22878. // Sprites
  22879. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22880. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22881. this.setPointerOverSprite(pickResult.pickedSprite);
  22882. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22883. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22884. }
  22885. else {
  22886. canvas.style.cursor = this.hoverCursor;
  22887. }
  22888. }
  22889. else {
  22890. this.setPointerOverSprite(null);
  22891. // Restore pointer
  22892. canvas.style.cursor = this.defaultCursor;
  22893. }
  22894. }
  22895. if (pickResult) {
  22896. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22897. if (this.onPointerMove) {
  22898. this.onPointerMove(evt, pickResult, type);
  22899. }
  22900. if (this.onPointerObservable.hasObservers()) {
  22901. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22902. this.onPointerObservable.notifyObservers(pi, type);
  22903. }
  22904. }
  22905. return this;
  22906. };
  22907. /**
  22908. * Use this method to simulate a pointer down on a mesh
  22909. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22910. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22911. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22912. * @returns the current scene
  22913. */
  22914. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22915. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22916. return this._processPointerDown(pickResult, evt);
  22917. };
  22918. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22919. var _this = this;
  22920. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22921. this._pickedDownMesh = pickResult.pickedMesh;
  22922. var actionManager = pickResult.pickedMesh.actionManager;
  22923. if (actionManager) {
  22924. if (actionManager.hasPickTriggers) {
  22925. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22926. switch (evt.button) {
  22927. case 0:
  22928. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22929. break;
  22930. case 1:
  22931. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22932. break;
  22933. case 2:
  22934. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22935. break;
  22936. }
  22937. }
  22938. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22939. window.setTimeout(function () {
  22940. 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);
  22941. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22942. if (_this._totalPointersPressed !== 0 &&
  22943. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22944. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22945. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22946. _this._startingPointerTime = 0;
  22947. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22948. }
  22949. }
  22950. }, Scene.LongPressDelay);
  22951. }
  22952. }
  22953. }
  22954. if (pickResult) {
  22955. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22956. if (this.onPointerDown) {
  22957. this.onPointerDown(evt, pickResult, type);
  22958. }
  22959. if (this.onPointerObservable.hasObservers()) {
  22960. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22961. this.onPointerObservable.notifyObservers(pi, type);
  22962. }
  22963. }
  22964. return this;
  22965. };
  22966. /**
  22967. * Use this method to simulate a pointer up on a mesh
  22968. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22969. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22970. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22971. * @returns the current scene
  22972. */
  22973. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22974. var evt = new PointerEvent("pointerup", pointerEventInit);
  22975. var clickInfo = new ClickInfo();
  22976. clickInfo.singleClick = true;
  22977. clickInfo.ignore = true;
  22978. return this._processPointerUp(pickResult, evt, clickInfo);
  22979. };
  22980. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22981. if (pickResult && pickResult && pickResult.pickedMesh) {
  22982. this._pickedUpMesh = pickResult.pickedMesh;
  22983. if (this._pickedDownMesh === this._pickedUpMesh) {
  22984. if (this.onPointerPick) {
  22985. this.onPointerPick(evt, pickResult);
  22986. }
  22987. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22988. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22989. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22990. this.onPointerObservable.notifyObservers(pi, type_1);
  22991. }
  22992. }
  22993. if (pickResult.pickedMesh.actionManager) {
  22994. if (clickInfo.ignore) {
  22995. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22996. }
  22997. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22998. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22999. }
  23000. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  23001. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  23002. }
  23003. }
  23004. }
  23005. if (this._pickedDownMesh &&
  23006. this._pickedDownMesh.actionManager &&
  23007. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  23008. this._pickedDownMesh !== this._pickedUpMesh) {
  23009. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  23010. }
  23011. var type = BABYLON.PointerEventTypes.POINTERUP;
  23012. if (this.onPointerObservable.hasObservers()) {
  23013. if (!clickInfo.ignore) {
  23014. if (!clickInfo.hasSwiped) {
  23015. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  23016. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  23017. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  23018. this.onPointerObservable.notifyObservers(pi, type_2);
  23019. }
  23020. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23021. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23022. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  23023. this.onPointerObservable.notifyObservers(pi, type_3);
  23024. }
  23025. }
  23026. }
  23027. else {
  23028. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  23029. this.onPointerObservable.notifyObservers(pi, type);
  23030. }
  23031. }
  23032. if (this.onPointerUp) {
  23033. this.onPointerUp(evt, pickResult, type);
  23034. }
  23035. return this;
  23036. };
  23037. /**
  23038. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  23039. * @param attachUp defines if you want to attach events to pointerup
  23040. * @param attachDown defines if you want to attach events to pointerdown
  23041. * @param attachMove defines if you want to attach events to pointermove
  23042. */
  23043. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  23044. var _this = this;
  23045. if (attachUp === void 0) { attachUp = true; }
  23046. if (attachDown === void 0) { attachDown = true; }
  23047. if (attachMove === void 0) { attachMove = true; }
  23048. this._initActionManager = function (act, clickInfo) {
  23049. if (!_this._meshPickProceed) {
  23050. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  23051. _this._currentPickResult = pickResult;
  23052. if (pickResult) {
  23053. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  23054. }
  23055. _this._meshPickProceed = true;
  23056. }
  23057. return act;
  23058. };
  23059. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  23060. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  23061. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  23062. btn !== _this._previousButtonPressed) {
  23063. _this._doubleClickOccured = false;
  23064. clickInfo.singleClick = true;
  23065. clickInfo.ignore = false;
  23066. cb(clickInfo, _this._currentPickResult);
  23067. }
  23068. };
  23069. this._initClickEvent = function (obs1, obs2, evt, cb) {
  23070. var clickInfo = new ClickInfo();
  23071. _this._currentPickResult = null;
  23072. var act = null;
  23073. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  23074. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  23075. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  23076. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  23077. act = _this._initActionManager(act, clickInfo);
  23078. if (act)
  23079. checkPicking = act.hasPickTriggers;
  23080. }
  23081. if (checkPicking) {
  23082. var btn = evt.button;
  23083. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  23084. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  23085. if (!clickInfo.hasSwiped) {
  23086. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  23087. if (!checkSingleClickImmediately) {
  23088. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  23089. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  23090. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  23091. act = _this._initActionManager(act, clickInfo);
  23092. if (act)
  23093. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  23094. }
  23095. }
  23096. if (checkSingleClickImmediately) {
  23097. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  23098. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  23099. btn !== _this._previousButtonPressed) {
  23100. clickInfo.singleClick = true;
  23101. cb(clickInfo, _this._currentPickResult);
  23102. }
  23103. }
  23104. else {
  23105. // wait that no double click has been raised during the double click delay
  23106. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  23107. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  23108. }
  23109. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  23110. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  23111. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  23112. act = _this._initActionManager(act, clickInfo);
  23113. if (act)
  23114. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  23115. }
  23116. if (checkDoubleClick) {
  23117. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  23118. if (btn === _this._previousButtonPressed &&
  23119. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  23120. !_this._doubleClickOccured) {
  23121. // pointer has not moved for 2 clicks, it's a double click
  23122. if (!clickInfo.hasSwiped &&
  23123. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  23124. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  23125. _this._previousStartingPointerTime = 0;
  23126. _this._doubleClickOccured = true;
  23127. clickInfo.doubleClick = true;
  23128. clickInfo.ignore = false;
  23129. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  23130. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  23131. }
  23132. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  23133. cb(clickInfo, _this._currentPickResult);
  23134. }
  23135. else {
  23136. _this._doubleClickOccured = false;
  23137. _this._previousStartingPointerTime = _this._startingPointerTime;
  23138. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  23139. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  23140. _this._previousButtonPressed = btn;
  23141. if (Scene.ExclusiveDoubleClickMode) {
  23142. if (_this._previousDelayedSimpleClickTimeout) {
  23143. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  23144. }
  23145. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  23146. cb(clickInfo, _this._previousPickResult);
  23147. }
  23148. else {
  23149. cb(clickInfo, _this._currentPickResult);
  23150. }
  23151. }
  23152. }
  23153. else {
  23154. _this._doubleClickOccured = false;
  23155. _this._previousStartingPointerTime = _this._startingPointerTime;
  23156. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  23157. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  23158. _this._previousButtonPressed = btn;
  23159. }
  23160. }
  23161. }
  23162. }
  23163. clickInfo.ignore = true;
  23164. cb(clickInfo, _this._currentPickResult);
  23165. };
  23166. this._spritePredicate = function (sprite) {
  23167. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  23168. };
  23169. this._onPointerMove = function (evt) {
  23170. _this._updatePointerPosition(evt);
  23171. // PreObservable support
  23172. if (_this.onPrePointerObservable.hasObservers()) {
  23173. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  23174. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23175. _this.onPrePointerObservable.notifyObservers(pi, type);
  23176. if (pi.skipOnPointerObservable) {
  23177. return;
  23178. }
  23179. }
  23180. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23181. return;
  23182. }
  23183. if (!_this.pointerMovePredicate) {
  23184. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  23185. }
  23186. // Meshes
  23187. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  23188. _this._processPointerMove(pickResult, evt);
  23189. };
  23190. this._onPointerDown = function (evt) {
  23191. _this._totalPointersPressed++;
  23192. _this._pickedDownMesh = null;
  23193. _this._meshPickProceed = false;
  23194. _this._updatePointerPosition(evt);
  23195. if (_this.preventDefaultOnPointerDown && canvas) {
  23196. evt.preventDefault();
  23197. canvas.focus();
  23198. }
  23199. // PreObservable support
  23200. if (_this.onPrePointerObservable.hasObservers()) {
  23201. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  23202. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23203. _this.onPrePointerObservable.notifyObservers(pi, type);
  23204. if (pi.skipOnPointerObservable) {
  23205. return;
  23206. }
  23207. }
  23208. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23209. return;
  23210. }
  23211. _this._startingPointerPosition.x = _this._pointerX;
  23212. _this._startingPointerPosition.y = _this._pointerY;
  23213. _this._startingPointerTime = new Date().getTime();
  23214. if (!_this.pointerDownPredicate) {
  23215. _this.pointerDownPredicate = function (mesh) {
  23216. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23217. };
  23218. }
  23219. // Meshes
  23220. _this._pickedDownMesh = null;
  23221. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  23222. _this._processPointerDown(pickResult, evt);
  23223. // Sprites
  23224. _this._pickedDownSprite = null;
  23225. if (_this.spriteManagers.length > 0) {
  23226. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23227. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  23228. if (pickResult.pickedSprite.actionManager) {
  23229. _this._pickedDownSprite = pickResult.pickedSprite;
  23230. switch (evt.button) {
  23231. case 0:
  23232. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23233. break;
  23234. case 1:
  23235. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23236. break;
  23237. case 2:
  23238. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23239. break;
  23240. }
  23241. if (pickResult.pickedSprite.actionManager) {
  23242. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23243. }
  23244. }
  23245. }
  23246. }
  23247. };
  23248. this._onPointerUp = function (evt) {
  23249. if (_this._totalPointersPressed === 0) {
  23250. return; // So we need to test it the pointer down was pressed before.
  23251. }
  23252. _this._totalPointersPressed--;
  23253. _this._pickedUpMesh = null;
  23254. _this._meshPickProceed = false;
  23255. _this._updatePointerPosition(evt);
  23256. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  23257. // PreObservable support
  23258. if (_this.onPrePointerObservable.hasObservers()) {
  23259. if (!clickInfo.ignore) {
  23260. if (!clickInfo.hasSwiped) {
  23261. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  23262. var type = BABYLON.PointerEventTypes.POINTERTAP;
  23263. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23264. _this.onPrePointerObservable.notifyObservers(pi, type);
  23265. if (pi.skipOnPointerObservable) {
  23266. return;
  23267. }
  23268. }
  23269. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23270. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23271. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23272. _this.onPrePointerObservable.notifyObservers(pi, type);
  23273. if (pi.skipOnPointerObservable) {
  23274. return;
  23275. }
  23276. }
  23277. }
  23278. }
  23279. else {
  23280. var type = BABYLON.PointerEventTypes.POINTERUP;
  23281. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23282. _this.onPrePointerObservable.notifyObservers(pi, type);
  23283. if (pi.skipOnPointerObservable) {
  23284. return;
  23285. }
  23286. }
  23287. }
  23288. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23289. return;
  23290. }
  23291. if (!_this.pointerUpPredicate) {
  23292. _this.pointerUpPredicate = function (mesh) {
  23293. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23294. };
  23295. }
  23296. // Meshes
  23297. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23298. _this._initActionManager(null, clickInfo);
  23299. }
  23300. if (!pickResult) {
  23301. pickResult = _this._currentPickResult;
  23302. }
  23303. _this._processPointerUp(pickResult, evt, clickInfo);
  23304. // Sprites
  23305. if (_this.spriteManagers.length > 0) {
  23306. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23307. if (spritePickResult) {
  23308. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23309. if (spritePickResult.pickedSprite.actionManager) {
  23310. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23311. if (spritePickResult.pickedSprite.actionManager) {
  23312. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23313. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23314. }
  23315. }
  23316. }
  23317. }
  23318. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23319. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23320. }
  23321. }
  23322. }
  23323. _this._previousPickResult = _this._currentPickResult;
  23324. });
  23325. };
  23326. this._onKeyDown = function (evt) {
  23327. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23328. if (_this.onPreKeyboardObservable.hasObservers()) {
  23329. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23330. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23331. if (pi.skipOnPointerObservable) {
  23332. return;
  23333. }
  23334. }
  23335. if (_this.onKeyboardObservable.hasObservers()) {
  23336. var pi = new BABYLON.KeyboardInfo(type, evt);
  23337. _this.onKeyboardObservable.notifyObservers(pi, type);
  23338. }
  23339. if (_this.actionManager) {
  23340. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23341. }
  23342. };
  23343. this._onKeyUp = function (evt) {
  23344. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23345. if (_this.onPreKeyboardObservable.hasObservers()) {
  23346. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23347. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23348. if (pi.skipOnPointerObservable) {
  23349. return;
  23350. }
  23351. }
  23352. if (_this.onKeyboardObservable.hasObservers()) {
  23353. var pi = new BABYLON.KeyboardInfo(type, evt);
  23354. _this.onKeyboardObservable.notifyObservers(pi, type);
  23355. }
  23356. if (_this.actionManager) {
  23357. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23358. }
  23359. };
  23360. var engine = this.getEngine();
  23361. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23362. if (!canvas) {
  23363. return;
  23364. }
  23365. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23366. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23367. });
  23368. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23369. if (!canvas) {
  23370. return;
  23371. }
  23372. canvas.removeEventListener("keydown", _this._onKeyDown);
  23373. canvas.removeEventListener("keyup", _this._onKeyUp);
  23374. });
  23375. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23376. var canvas = this._engine.getRenderingCanvas();
  23377. if (!canvas) {
  23378. return;
  23379. }
  23380. if (attachMove) {
  23381. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23382. // Wheel
  23383. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23384. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23385. }
  23386. if (attachDown) {
  23387. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23388. }
  23389. if (attachUp) {
  23390. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23391. }
  23392. canvas.tabIndex = 1;
  23393. };
  23394. /** Detaches all event handlers*/
  23395. Scene.prototype.detachControl = function () {
  23396. var engine = this.getEngine();
  23397. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23398. var canvas = engine.getRenderingCanvas();
  23399. if (!canvas) {
  23400. return;
  23401. }
  23402. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23403. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23404. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23405. if (this._onCanvasBlurObserver) {
  23406. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23407. }
  23408. if (this._onCanvasFocusObserver) {
  23409. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23410. }
  23411. // Wheel
  23412. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23413. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23414. // Keyboard
  23415. canvas.removeEventListener("keydown", this._onKeyDown);
  23416. canvas.removeEventListener("keyup", this._onKeyUp);
  23417. // Observables
  23418. this.onKeyboardObservable.clear();
  23419. this.onPreKeyboardObservable.clear();
  23420. this.onPointerObservable.clear();
  23421. this.onPrePointerObservable.clear();
  23422. };
  23423. /**
  23424. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23425. * Delay loaded resources are not taking in account
  23426. * @return true if all required resources are ready
  23427. */
  23428. Scene.prototype.isReady = function () {
  23429. if (this._isDisposed) {
  23430. return false;
  23431. }
  23432. if (this._pendingData.length > 0) {
  23433. return false;
  23434. }
  23435. var index;
  23436. var engine = this.getEngine();
  23437. // Geometries
  23438. for (index = 0; index < this._geometries.length; index++) {
  23439. var geometry = this._geometries[index];
  23440. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23441. return false;
  23442. }
  23443. }
  23444. // Meshes
  23445. for (index = 0; index < this.meshes.length; index++) {
  23446. var mesh = this.meshes[index];
  23447. if (!mesh.isEnabled()) {
  23448. continue;
  23449. }
  23450. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23451. continue;
  23452. }
  23453. if (!mesh.isReady(true)) {
  23454. return false;
  23455. }
  23456. // Effect layers
  23457. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23458. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23459. var layer = _a[_i];
  23460. if (!layer.hasMesh(mesh)) {
  23461. continue;
  23462. }
  23463. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23464. var subMesh = _c[_b];
  23465. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23466. return false;
  23467. }
  23468. }
  23469. }
  23470. }
  23471. // Post-processes
  23472. if (this.activeCameras && this.activeCameras.length > 0) {
  23473. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  23474. var camera = _e[_d];
  23475. if (!camera.isReady(true)) {
  23476. return false;
  23477. }
  23478. }
  23479. }
  23480. else if (this.activeCamera) {
  23481. if (!this.activeCamera.isReady(true)) {
  23482. return false;
  23483. }
  23484. }
  23485. // Particles
  23486. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  23487. var particleSystem = _g[_f];
  23488. if (!particleSystem.isReady()) {
  23489. return false;
  23490. }
  23491. }
  23492. return true;
  23493. };
  23494. /** Resets all cached information relative to material (including effect and visibility) */
  23495. Scene.prototype.resetCachedMaterial = function () {
  23496. this._cachedMaterial = null;
  23497. this._cachedEffect = null;
  23498. this._cachedVisibility = null;
  23499. };
  23500. /**
  23501. * Registers a function to be called before every frame render
  23502. * @param func defines the function to register
  23503. */
  23504. Scene.prototype.registerBeforeRender = function (func) {
  23505. this.onBeforeRenderObservable.add(func);
  23506. };
  23507. /**
  23508. * Unregisters a function called before every frame render
  23509. * @param func defines the function to unregister
  23510. */
  23511. Scene.prototype.unregisterBeforeRender = function (func) {
  23512. this.onBeforeRenderObservable.removeCallback(func);
  23513. };
  23514. /**
  23515. * Registers a function to be called after every frame render
  23516. * @param func defines the function to register
  23517. */
  23518. Scene.prototype.registerAfterRender = function (func) {
  23519. this.onAfterRenderObservable.add(func);
  23520. };
  23521. /**
  23522. * Unregisters a function called after every frame render
  23523. * @param func defines the function to unregister
  23524. */
  23525. Scene.prototype.unregisterAfterRender = function (func) {
  23526. this.onAfterRenderObservable.removeCallback(func);
  23527. };
  23528. Scene.prototype._executeOnceBeforeRender = function (func) {
  23529. var _this = this;
  23530. var execFunc = function () {
  23531. func();
  23532. setTimeout(function () {
  23533. _this.unregisterBeforeRender(execFunc);
  23534. });
  23535. };
  23536. this.registerBeforeRender(execFunc);
  23537. };
  23538. /**
  23539. * The provided function will run before render once and will be disposed afterwards.
  23540. * A timeout delay can be provided so that the function will be executed in N ms.
  23541. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23542. * @param func The function to be executed.
  23543. * @param timeout optional delay in ms
  23544. */
  23545. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23546. var _this = this;
  23547. if (timeout !== undefined) {
  23548. setTimeout(function () {
  23549. _this._executeOnceBeforeRender(func);
  23550. }, timeout);
  23551. }
  23552. else {
  23553. this._executeOnceBeforeRender(func);
  23554. }
  23555. };
  23556. /** @ignore */
  23557. Scene.prototype._addPendingData = function (data) {
  23558. this._pendingData.push(data);
  23559. };
  23560. /** @ignore */
  23561. Scene.prototype._removePendingData = function (data) {
  23562. var wasLoading = this.isLoading;
  23563. var index = this._pendingData.indexOf(data);
  23564. if (index !== -1) {
  23565. this._pendingData.splice(index, 1);
  23566. }
  23567. if (wasLoading && !this.isLoading) {
  23568. this.onDataLoadedObservable.notifyObservers(this);
  23569. }
  23570. };
  23571. /**
  23572. * Returns the number of items waiting to be loaded
  23573. * @returns the number of items waiting to be loaded
  23574. */
  23575. Scene.prototype.getWaitingItemsCount = function () {
  23576. return this._pendingData.length;
  23577. };
  23578. Object.defineProperty(Scene.prototype, "isLoading", {
  23579. /**
  23580. * Returns a boolean indicating if the scene is still loading data
  23581. */
  23582. get: function () {
  23583. return this._pendingData.length > 0;
  23584. },
  23585. enumerable: true,
  23586. configurable: true
  23587. });
  23588. /**
  23589. * Registers a function to be executed when the scene is ready
  23590. * @param {Function} func - the function to be executed
  23591. */
  23592. Scene.prototype.executeWhenReady = function (func) {
  23593. var _this = this;
  23594. this.onReadyObservable.add(func);
  23595. if (this._executeWhenReadyTimeoutId !== -1) {
  23596. return;
  23597. }
  23598. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23599. _this._checkIsReady();
  23600. }, 150);
  23601. };
  23602. /**
  23603. * Returns a promise that resolves when the scene is ready
  23604. * @returns A promise that resolves when the scene is ready
  23605. */
  23606. Scene.prototype.whenReadyAsync = function () {
  23607. var _this = this;
  23608. return new Promise(function (resolve) {
  23609. _this.executeWhenReady(function () {
  23610. resolve();
  23611. });
  23612. });
  23613. };
  23614. /** @ignore */
  23615. Scene.prototype._checkIsReady = function () {
  23616. var _this = this;
  23617. if (this.isReady()) {
  23618. this.onReadyObservable.notifyObservers(this);
  23619. this.onReadyObservable.clear();
  23620. this._executeWhenReadyTimeoutId = -1;
  23621. return;
  23622. }
  23623. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23624. _this._checkIsReady();
  23625. }, 150);
  23626. };
  23627. // Animations
  23628. /**
  23629. * Will start the animation sequence of a given target
  23630. * @param target defines the target
  23631. * @param from defines from which frame should animation start
  23632. * @param to defines until which frame should animation run.
  23633. * @param weight defines the weight to apply to the animation (1.0 by default)
  23634. * @param loop defines if the animation loops
  23635. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23636. * @param onAnimationEnd defines the function to be executed when the animation ends
  23637. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23638. * @returns the animatable object created for this animation
  23639. */
  23640. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23641. if (weight === void 0) { weight = 1.0; }
  23642. if (speedRatio === void 0) { speedRatio = 1.0; }
  23643. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23644. returnedAnimatable.weight = weight;
  23645. return returnedAnimatable;
  23646. };
  23647. /**
  23648. * Will start the animation sequence of a given target
  23649. * @param target defines the target
  23650. * @param from defines from which frame should animation start
  23651. * @param to defines until which frame should animation run.
  23652. * @param loop defines if the animation loops
  23653. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23654. * @param onAnimationEnd defines the function to be executed when the animation ends
  23655. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23656. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23657. * @returns the animatable object created for this animation
  23658. */
  23659. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23660. if (speedRatio === void 0) { speedRatio = 1.0; }
  23661. if (stopCurrent === void 0) { stopCurrent = true; }
  23662. if (from > to && speedRatio > 0) {
  23663. speedRatio *= -1;
  23664. }
  23665. if (stopCurrent) {
  23666. this.stopAnimation(target);
  23667. }
  23668. if (!animatable) {
  23669. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23670. }
  23671. // Local animations
  23672. if (target.animations) {
  23673. animatable.appendAnimations(target, target.animations);
  23674. }
  23675. // Children animations
  23676. if (target.getAnimatables) {
  23677. var animatables = target.getAnimatables();
  23678. for (var index = 0; index < animatables.length; index++) {
  23679. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23680. }
  23681. }
  23682. animatable.reset();
  23683. return animatable;
  23684. };
  23685. /**
  23686. * Begin a new animation on a given node
  23687. * @param target defines the target where the animation will take place
  23688. * @param animations defines the list of animations to start
  23689. * @param from defines the initial value
  23690. * @param to defines the final value
  23691. * @param loop defines if you want animation to loop (off by default)
  23692. * @param speedRatio defines the speed ratio to apply to all animations
  23693. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23694. * @returns the list of created animatables
  23695. */
  23696. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23697. if (speedRatio === undefined) {
  23698. speedRatio = 1.0;
  23699. }
  23700. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23701. return animatable;
  23702. };
  23703. /**
  23704. * Begin a new animation on a given node and its hierarchy
  23705. * @param target defines the root node where the animation will take place
  23706. * @param 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.
  23707. * @param animations defines the list of animations to start
  23708. * @param from defines the initial value
  23709. * @param to defines the final value
  23710. * @param loop defines if you want animation to loop (off by default)
  23711. * @param speedRatio defines the speed ratio to apply to all animations
  23712. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23713. * @returns the list of animatables created for all nodes
  23714. */
  23715. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23716. var children = target.getDescendants(directDescendantsOnly);
  23717. var result = [];
  23718. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23719. var child = children_1[_i];
  23720. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23721. }
  23722. return result;
  23723. };
  23724. /**
  23725. * Gets the animatable associated with a specific target
  23726. * @param target defines the target of the animatable
  23727. * @returns the required animatable if found
  23728. */
  23729. Scene.prototype.getAnimatableByTarget = function (target) {
  23730. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23731. if (this._activeAnimatables[index].target === target) {
  23732. return this._activeAnimatables[index];
  23733. }
  23734. }
  23735. return null;
  23736. };
  23737. /**
  23738. * Gets all animatables associated with a given target
  23739. * @param target defines the target to look animatables for
  23740. * @returns an array of Animatables
  23741. */
  23742. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23743. var result = [];
  23744. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23745. if (this._activeAnimatables[index].target === target) {
  23746. result.push(this._activeAnimatables[index]);
  23747. }
  23748. }
  23749. return result;
  23750. };
  23751. Object.defineProperty(Scene.prototype, "animatables", {
  23752. /**
  23753. * Gets all animatable attached to the scene
  23754. */
  23755. get: function () {
  23756. return this._activeAnimatables;
  23757. },
  23758. enumerable: true,
  23759. configurable: true
  23760. });
  23761. /**
  23762. * Will stop the animation of the given target
  23763. * @param target - the target
  23764. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23765. */
  23766. Scene.prototype.stopAnimation = function (target, animationName) {
  23767. var animatables = this.getAllAnimatablesByTarget(target);
  23768. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23769. var animatable = animatables_1[_i];
  23770. animatable.stop(animationName);
  23771. }
  23772. };
  23773. /**
  23774. * Stops and removes all animations that have been applied to the scene
  23775. */
  23776. Scene.prototype.stopAllAnimations = function () {
  23777. if (this._activeAnimatables) {
  23778. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23779. this._activeAnimatables[i].stop();
  23780. }
  23781. this._activeAnimatables = [];
  23782. }
  23783. };
  23784. Scene.prototype._animate = function () {
  23785. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23786. return;
  23787. }
  23788. // Getting time
  23789. var now = BABYLON.Tools.Now;
  23790. if (!this._animationTimeLast) {
  23791. if (this._pendingData.length > 0) {
  23792. return;
  23793. }
  23794. this._animationTimeLast = now;
  23795. }
  23796. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23797. this._animationTime += deltaTime;
  23798. this._animationTimeLast = now;
  23799. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23800. this._activeAnimatables[index]._animate(this._animationTime);
  23801. }
  23802. // Late animation bindings
  23803. this._processLateAnimationBindings();
  23804. };
  23805. /** @ignore */
  23806. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23807. var target = runtimeAnimation.target;
  23808. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23809. if (!target._lateAnimationHolders) {
  23810. target._lateAnimationHolders = {};
  23811. }
  23812. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23813. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23814. totalWeight: 0,
  23815. animations: []
  23816. };
  23817. }
  23818. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23819. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23820. };
  23821. Scene.prototype._processLateAnimationBindings = function () {
  23822. if (!this._registeredForLateAnimationBindings.length) {
  23823. return;
  23824. }
  23825. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23826. var target = this._registeredForLateAnimationBindings.data[index];
  23827. for (var path in target._lateAnimationHolders) {
  23828. var holder = target._lateAnimationHolders[path];
  23829. // Sanity check
  23830. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23831. continue;
  23832. }
  23833. var normalizer = 1.0;
  23834. var finalValue = void 0;
  23835. if (holder.totalWeight < 1.0) {
  23836. // We need to mix the original value in
  23837. var originalValue = holder.animations[0].originalValue;
  23838. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23839. }
  23840. else {
  23841. // We need to normalize the weights
  23842. normalizer = holder.totalWeight;
  23843. }
  23844. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23845. var runtimeAnimation = holder.animations[animIndex];
  23846. if (finalValue) {
  23847. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23848. }
  23849. else {
  23850. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23851. }
  23852. }
  23853. runtimeAnimation.target[path] = finalValue;
  23854. }
  23855. target._lateAnimationHolders = {};
  23856. }
  23857. this._registeredForLateAnimationBindings.reset();
  23858. };
  23859. // Matrix
  23860. /** @ignore */
  23861. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23862. this._useAlternateCameraConfiguration = active;
  23863. };
  23864. /**
  23865. * Gets the current view matrix
  23866. * @returns a Matrix
  23867. */
  23868. Scene.prototype.getViewMatrix = function () {
  23869. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23870. };
  23871. /**
  23872. * Gets the current projection matrix
  23873. * @returns a Matrix
  23874. */
  23875. Scene.prototype.getProjectionMatrix = function () {
  23876. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23877. };
  23878. /**
  23879. * Gets the current transform matrix
  23880. * @returns a Matrix made of View * Projection
  23881. */
  23882. Scene.prototype.getTransformMatrix = function () {
  23883. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23884. };
  23885. /**
  23886. * Sets the current transform matrix
  23887. * @param view defines the View matrix to use
  23888. * @param projection defines the Projection matrix to use
  23889. */
  23890. Scene.prototype.setTransformMatrix = function (view, projection) {
  23891. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23892. return;
  23893. }
  23894. this._viewUpdateFlag = view.updateFlag;
  23895. this._projectionUpdateFlag = projection.updateFlag;
  23896. this._viewMatrix = view;
  23897. this._projectionMatrix = projection;
  23898. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23899. // Update frustum
  23900. if (!this._frustumPlanes) {
  23901. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23902. }
  23903. else {
  23904. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23905. }
  23906. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23907. var otherCamera = this.activeCamera._alternateCamera;
  23908. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23909. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23910. }
  23911. if (this._sceneUbo.useUbo) {
  23912. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23913. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23914. this._sceneUbo.update();
  23915. }
  23916. };
  23917. /** @ignore */
  23918. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23919. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23920. return;
  23921. }
  23922. this._alternateViewUpdateFlag = view.updateFlag;
  23923. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23924. this._alternateViewMatrix = view;
  23925. this._alternateProjectionMatrix = projection;
  23926. if (!this._alternateTransformMatrix) {
  23927. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23928. }
  23929. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23930. if (!this._alternateSceneUbo) {
  23931. this._createAlternateUbo();
  23932. }
  23933. if (this._alternateSceneUbo.useUbo) {
  23934. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23935. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23936. this._alternateSceneUbo.update();
  23937. }
  23938. };
  23939. /**
  23940. * Gets the uniform buffer used to store scene data
  23941. * @returns a UniformBuffer
  23942. */
  23943. Scene.prototype.getSceneUniformBuffer = function () {
  23944. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23945. };
  23946. /**
  23947. * Gets an unique (relatively to the current scene) Id
  23948. * @returns an unique number for the scene
  23949. */
  23950. Scene.prototype.getUniqueId = function () {
  23951. var result = Scene._uniqueIdCounter;
  23952. Scene._uniqueIdCounter++;
  23953. return result;
  23954. };
  23955. /**
  23956. * Add a mesh to the list of scene's meshes
  23957. * @param newMesh defines the mesh to add
  23958. */
  23959. Scene.prototype.addMesh = function (newMesh) {
  23960. this.meshes.push(newMesh);
  23961. //notify the collision coordinator
  23962. if (this.collisionCoordinator) {
  23963. this.collisionCoordinator.onMeshAdded(newMesh);
  23964. }
  23965. newMesh._resyncLightSources();
  23966. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23967. };
  23968. /**
  23969. * Remove a mesh for the list of scene's meshes
  23970. * @param toRemove defines the mesh to remove
  23971. * @returns the index where the mesh was in the mesh list
  23972. */
  23973. Scene.prototype.removeMesh = function (toRemove) {
  23974. var index = this.meshes.indexOf(toRemove);
  23975. if (index !== -1) {
  23976. // Remove from the scene if mesh found
  23977. this.meshes.splice(index, 1);
  23978. }
  23979. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23980. return index;
  23981. };
  23982. /**
  23983. * Add a transform node to the list of scene's transform nodes
  23984. * @param newTransformNode defines the transform node to add
  23985. */
  23986. Scene.prototype.addTransformNode = function (newTransformNode) {
  23987. this.transformNodes.push(newTransformNode);
  23988. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23989. };
  23990. /**
  23991. * Remove a transform node for the list of scene's transform nodes
  23992. * @param toRemove defines the transform node to remove
  23993. * @returns the index where the transform node was in the transform node list
  23994. */
  23995. Scene.prototype.removeTransformNode = function (toRemove) {
  23996. var index = this.transformNodes.indexOf(toRemove);
  23997. if (index !== -1) {
  23998. // Remove from the scene if found
  23999. this.transformNodes.splice(index, 1);
  24000. }
  24001. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  24002. return index;
  24003. };
  24004. /**
  24005. * Remove a skeleton for the list of scene's skeletons
  24006. * @param toRemove defines the skeleton to remove
  24007. * @returns the index where the skeleton was in the skeleton list
  24008. */
  24009. Scene.prototype.removeSkeleton = function (toRemove) {
  24010. var index = this.skeletons.indexOf(toRemove);
  24011. if (index !== -1) {
  24012. // Remove from the scene if found
  24013. this.skeletons.splice(index, 1);
  24014. }
  24015. return index;
  24016. };
  24017. /**
  24018. * Remove a morph target for the list of scene's morph targets
  24019. * @param toRemove defines the morph target to remove
  24020. * @returns the index where the morph target was in the morph target list
  24021. */
  24022. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  24023. var index = this.morphTargetManagers.indexOf(toRemove);
  24024. if (index !== -1) {
  24025. // Remove from the scene if found
  24026. this.morphTargetManagers.splice(index, 1);
  24027. }
  24028. return index;
  24029. };
  24030. /**
  24031. * Remove a light for the list of scene's lights
  24032. * @param toRemove defines the light to remove
  24033. * @returns the index where the light was in the light list
  24034. */
  24035. Scene.prototype.removeLight = function (toRemove) {
  24036. var index = this.lights.indexOf(toRemove);
  24037. if (index !== -1) {
  24038. // Remove from meshes
  24039. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  24040. var mesh = _a[_i];
  24041. mesh._removeLightSource(toRemove);
  24042. }
  24043. // Remove from the scene if mesh found
  24044. this.lights.splice(index, 1);
  24045. this.sortLightsByPriority();
  24046. }
  24047. this.onLightRemovedObservable.notifyObservers(toRemove);
  24048. return index;
  24049. };
  24050. /**
  24051. * Remove a camera for the list of scene's cameras
  24052. * @param toRemove defines the camera to remove
  24053. * @returns the index where the camera was in the camera list
  24054. */
  24055. Scene.prototype.removeCamera = function (toRemove) {
  24056. var index = this.cameras.indexOf(toRemove);
  24057. if (index !== -1) {
  24058. // Remove from the scene if mesh found
  24059. this.cameras.splice(index, 1);
  24060. }
  24061. // Remove from activeCameras
  24062. var index2 = this.activeCameras.indexOf(toRemove);
  24063. if (index2 !== -1) {
  24064. // Remove from the scene if mesh found
  24065. this.activeCameras.splice(index2, 1);
  24066. }
  24067. // Reset the activeCamera
  24068. if (this.activeCamera === toRemove) {
  24069. if (this.cameras.length > 0) {
  24070. this.activeCamera = this.cameras[0];
  24071. }
  24072. else {
  24073. this.activeCamera = null;
  24074. }
  24075. }
  24076. this.onCameraRemovedObservable.notifyObservers(toRemove);
  24077. return index;
  24078. };
  24079. /**
  24080. * Remove a particle system for the list of scene's particle systems
  24081. * @param toRemove defines the particle system to remove
  24082. * @returns the index where the particle system was in the particle system list
  24083. */
  24084. Scene.prototype.removeParticleSystem = function (toRemove) {
  24085. var index = this.particleSystems.indexOf(toRemove);
  24086. if (index !== -1) {
  24087. this.particleSystems.splice(index, 1);
  24088. }
  24089. return index;
  24090. };
  24091. /**
  24092. * Remove a animation for the list of scene's animations
  24093. * @param toRemove defines the animation to remove
  24094. * @returns the index where the animation was in the animation list
  24095. */
  24096. Scene.prototype.removeAnimation = function (toRemove) {
  24097. var index = this.animations.indexOf(toRemove);
  24098. if (index !== -1) {
  24099. this.animations.splice(index, 1);
  24100. }
  24101. return index;
  24102. };
  24103. /**
  24104. * Removes the given animation group from this scene.
  24105. * @param toRemove The animation group to remove
  24106. * @returns The index of the removed animation group
  24107. */
  24108. Scene.prototype.removeAnimationGroup = function (toRemove) {
  24109. var index = this.animationGroups.indexOf(toRemove);
  24110. if (index !== -1) {
  24111. this.animationGroups.splice(index, 1);
  24112. }
  24113. return index;
  24114. };
  24115. /**
  24116. * Removes the given multi-material from this scene.
  24117. * @param toRemove The multi-material to remove
  24118. * @returns The index of the removed multi-material
  24119. */
  24120. Scene.prototype.removeMultiMaterial = function (toRemove) {
  24121. var index = this.multiMaterials.indexOf(toRemove);
  24122. if (index !== -1) {
  24123. this.multiMaterials.splice(index, 1);
  24124. }
  24125. return index;
  24126. };
  24127. /**
  24128. * Removes the given material from this scene.
  24129. * @param toRemove The material to remove
  24130. * @returns The index of the removed material
  24131. */
  24132. Scene.prototype.removeMaterial = function (toRemove) {
  24133. var index = this.materials.indexOf(toRemove);
  24134. if (index !== -1) {
  24135. this.materials.splice(index, 1);
  24136. }
  24137. return index;
  24138. };
  24139. /**
  24140. * Removes the given lens flare system from this scene.
  24141. * @param toRemove The lens flare system to remove
  24142. * @returns The index of the removed lens flare system
  24143. */
  24144. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  24145. var index = this.lensFlareSystems.indexOf(toRemove);
  24146. if (index !== -1) {
  24147. this.lensFlareSystems.splice(index, 1);
  24148. }
  24149. return index;
  24150. };
  24151. /**
  24152. * Removes the given action manager from this scene.
  24153. * @param toRemove The action manager to remove
  24154. * @returns The index of the removed action manager
  24155. */
  24156. Scene.prototype.removeActionManager = function (toRemove) {
  24157. var index = this._actionManagers.indexOf(toRemove);
  24158. if (index !== -1) {
  24159. this._actionManagers.splice(index, 1);
  24160. }
  24161. return index;
  24162. };
  24163. /**
  24164. * Removes the given texture from this scene.
  24165. * @param toRemove The texture to remove
  24166. * @returns The index of the removed texture
  24167. */
  24168. Scene.prototype.removeTexture = function (toRemove) {
  24169. var index = this.textures.indexOf(toRemove);
  24170. if (index !== -1) {
  24171. this.textures.splice(index, 1);
  24172. }
  24173. return index;
  24174. };
  24175. /**
  24176. * Adds the given light to this scene
  24177. * @param newLight The light to add
  24178. */
  24179. Scene.prototype.addLight = function (newLight) {
  24180. this.lights.push(newLight);
  24181. this.sortLightsByPriority();
  24182. // Add light to all meshes (To support if the light is removed and then readded)
  24183. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  24184. var mesh = _a[_i];
  24185. if (mesh._lightSources.indexOf(newLight) === -1) {
  24186. mesh._lightSources.push(newLight);
  24187. mesh._resyncLightSources();
  24188. }
  24189. }
  24190. this.onNewLightAddedObservable.notifyObservers(newLight);
  24191. };
  24192. /**
  24193. * Sorts the list list based on light priorities
  24194. */
  24195. Scene.prototype.sortLightsByPriority = function () {
  24196. if (this.requireLightSorting) {
  24197. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  24198. }
  24199. };
  24200. /**
  24201. * Adds the given camera to this scene
  24202. * @param newCamera The camera to add
  24203. */
  24204. Scene.prototype.addCamera = function (newCamera) {
  24205. this.cameras.push(newCamera);
  24206. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  24207. };
  24208. /**
  24209. * Adds the given skeleton to this scene
  24210. * @param newSkeleton The skeleton to add
  24211. */
  24212. Scene.prototype.addSkeleton = function (newSkeleton) {
  24213. this.skeletons.push(newSkeleton);
  24214. };
  24215. /**
  24216. * Adds the given particle system to this scene
  24217. * @param newParticleSystem The particle system to add
  24218. */
  24219. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  24220. this.particleSystems.push(newParticleSystem);
  24221. };
  24222. /**
  24223. * Adds the given animation to this scene
  24224. * @param newAnimation The animation to add
  24225. */
  24226. Scene.prototype.addAnimation = function (newAnimation) {
  24227. this.animations.push(newAnimation);
  24228. };
  24229. /**
  24230. * Adds the given animation group to this scene.
  24231. * @param newAnimationGroup The animation group to add
  24232. */
  24233. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  24234. this.animationGroups.push(newAnimationGroup);
  24235. };
  24236. /**
  24237. * Adds the given multi-material to this scene
  24238. * @param newMultiMaterial The multi-material to add
  24239. */
  24240. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  24241. this.multiMaterials.push(newMultiMaterial);
  24242. };
  24243. /**
  24244. * Adds the given material to this scene
  24245. * @param newMaterial The material to add
  24246. */
  24247. Scene.prototype.addMaterial = function (newMaterial) {
  24248. this.materials.push(newMaterial);
  24249. };
  24250. /**
  24251. * Adds the given morph target to this scene
  24252. * @param newMorphTargetManager The morph target to add
  24253. */
  24254. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  24255. this.morphTargetManagers.push(newMorphTargetManager);
  24256. };
  24257. /**
  24258. * Adds the given geometry to this scene
  24259. * @param newGeometry The geometry to add
  24260. */
  24261. Scene.prototype.addGeometry = function (newGeometry) {
  24262. this._geometries.push(newGeometry);
  24263. };
  24264. /**
  24265. * Adds the given lens flare system to this scene
  24266. * @param newLensFlareSystem The lens flare system to add
  24267. */
  24268. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  24269. this.lensFlareSystems.push(newLensFlareSystem);
  24270. };
  24271. /**
  24272. * Adds the given action manager to this scene
  24273. * @param newActionManager The action manager to add
  24274. */
  24275. Scene.prototype.addActionManager = function (newActionManager) {
  24276. this._actionManagers.push(newActionManager);
  24277. };
  24278. /**
  24279. * Adds the given texture to this scene.
  24280. * @param newTexture The texture to add
  24281. */
  24282. Scene.prototype.addTexture = function (newTexture) {
  24283. this.textures.push(newTexture);
  24284. };
  24285. /**
  24286. * Switch active camera
  24287. * @param newCamera defines the new active camera
  24288. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  24289. */
  24290. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  24291. if (attachControl === void 0) { attachControl = true; }
  24292. var canvas = this._engine.getRenderingCanvas();
  24293. if (!canvas) {
  24294. return;
  24295. }
  24296. if (this.activeCamera) {
  24297. this.activeCamera.detachControl(canvas);
  24298. }
  24299. this.activeCamera = newCamera;
  24300. if (attachControl) {
  24301. newCamera.attachControl(canvas);
  24302. }
  24303. };
  24304. /**
  24305. * sets the active camera of the scene using its ID
  24306. * @param id defines the camera's ID
  24307. * @return the new active camera or null if none found.
  24308. */
  24309. Scene.prototype.setActiveCameraByID = function (id) {
  24310. var camera = this.getCameraByID(id);
  24311. if (camera) {
  24312. this.activeCamera = camera;
  24313. return camera;
  24314. }
  24315. return null;
  24316. };
  24317. /**
  24318. * sets the active camera of the scene using its name
  24319. * @param name defines the camera's name
  24320. * @returns the new active camera or null if none found.
  24321. */
  24322. Scene.prototype.setActiveCameraByName = function (name) {
  24323. var camera = this.getCameraByName(name);
  24324. if (camera) {
  24325. this.activeCamera = camera;
  24326. return camera;
  24327. }
  24328. return null;
  24329. };
  24330. /**
  24331. * get an animation group using its name
  24332. * @param name defines the material's name
  24333. * @return the animation group or null if none found.
  24334. */
  24335. Scene.prototype.getAnimationGroupByName = function (name) {
  24336. for (var index = 0; index < this.animationGroups.length; index++) {
  24337. if (this.animationGroups[index].name === name) {
  24338. return this.animationGroups[index];
  24339. }
  24340. }
  24341. return null;
  24342. };
  24343. /**
  24344. * get a material using its id
  24345. * @param id defines the material's ID
  24346. * @return the material or null if none found.
  24347. */
  24348. Scene.prototype.getMaterialByID = function (id) {
  24349. for (var index = 0; index < this.materials.length; index++) {
  24350. if (this.materials[index].id === id) {
  24351. return this.materials[index];
  24352. }
  24353. }
  24354. return null;
  24355. };
  24356. /**
  24357. * Gets a material using its name
  24358. * @param name defines the material's name
  24359. * @return the material or null if none found.
  24360. */
  24361. Scene.prototype.getMaterialByName = function (name) {
  24362. for (var index = 0; index < this.materials.length; index++) {
  24363. if (this.materials[index].name === name) {
  24364. return this.materials[index];
  24365. }
  24366. }
  24367. return null;
  24368. };
  24369. /**
  24370. * Gets a lens flare system using its name
  24371. * @param name defines the name to look for
  24372. * @returns the lens flare system or null if not found
  24373. */
  24374. Scene.prototype.getLensFlareSystemByName = function (name) {
  24375. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  24376. if (this.lensFlareSystems[index].name === name) {
  24377. return this.lensFlareSystems[index];
  24378. }
  24379. }
  24380. return null;
  24381. };
  24382. /**
  24383. * Gets a lens flare system using its id
  24384. * @param id defines the id to look for
  24385. * @returns the lens flare system or null if not found
  24386. */
  24387. Scene.prototype.getLensFlareSystemByID = function (id) {
  24388. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  24389. if (this.lensFlareSystems[index].id === id) {
  24390. return this.lensFlareSystems[index];
  24391. }
  24392. }
  24393. return null;
  24394. };
  24395. /**
  24396. * Gets a camera using its id
  24397. * @param id defines the id to look for
  24398. * @returns the camera or null if not found
  24399. */
  24400. Scene.prototype.getCameraByID = function (id) {
  24401. for (var index = 0; index < this.cameras.length; index++) {
  24402. if (this.cameras[index].id === id) {
  24403. return this.cameras[index];
  24404. }
  24405. }
  24406. return null;
  24407. };
  24408. /**
  24409. * Gets a camera using its unique id
  24410. * @param uniqueId defines the unique id to look for
  24411. * @returns the camera or null if not found
  24412. */
  24413. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  24414. for (var index = 0; index < this.cameras.length; index++) {
  24415. if (this.cameras[index].uniqueId === uniqueId) {
  24416. return this.cameras[index];
  24417. }
  24418. }
  24419. return null;
  24420. };
  24421. /**
  24422. * Gets a camera using its name
  24423. * @param name defines the camera's name
  24424. * @return the camera or null if none found.
  24425. */
  24426. Scene.prototype.getCameraByName = function (name) {
  24427. for (var index = 0; index < this.cameras.length; index++) {
  24428. if (this.cameras[index].name === name) {
  24429. return this.cameras[index];
  24430. }
  24431. }
  24432. return null;
  24433. };
  24434. /**
  24435. * Gets a bone using its id
  24436. * @param id defines the bone's id
  24437. * @return the bone or null if not found
  24438. */
  24439. Scene.prototype.getBoneByID = function (id) {
  24440. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24441. var skeleton = this.skeletons[skeletonIndex];
  24442. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24443. if (skeleton.bones[boneIndex].id === id) {
  24444. return skeleton.bones[boneIndex];
  24445. }
  24446. }
  24447. }
  24448. return null;
  24449. };
  24450. /**
  24451. * Gets a bone using its id
  24452. * @param name defines the bone's name
  24453. * @return the bone or null if not found
  24454. */
  24455. Scene.prototype.getBoneByName = function (name) {
  24456. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24457. var skeleton = this.skeletons[skeletonIndex];
  24458. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24459. if (skeleton.bones[boneIndex].name === name) {
  24460. return skeleton.bones[boneIndex];
  24461. }
  24462. }
  24463. }
  24464. return null;
  24465. };
  24466. /**
  24467. * Gets a light node using its name
  24468. * @param name defines the the light's name
  24469. * @return the light or null if none found.
  24470. */
  24471. Scene.prototype.getLightByName = function (name) {
  24472. for (var index = 0; index < this.lights.length; index++) {
  24473. if (this.lights[index].name === name) {
  24474. return this.lights[index];
  24475. }
  24476. }
  24477. return null;
  24478. };
  24479. /**
  24480. * Gets a light node using its id
  24481. * @param id defines the light's id
  24482. * @return the light or null if none found.
  24483. */
  24484. Scene.prototype.getLightByID = function (id) {
  24485. for (var index = 0; index < this.lights.length; index++) {
  24486. if (this.lights[index].id === id) {
  24487. return this.lights[index];
  24488. }
  24489. }
  24490. return null;
  24491. };
  24492. /**
  24493. * Gets a light node using its scene-generated unique ID
  24494. * @param uniqueId defines the light's unique id
  24495. * @return the light or null if none found.
  24496. */
  24497. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  24498. for (var index = 0; index < this.lights.length; index++) {
  24499. if (this.lights[index].uniqueId === uniqueId) {
  24500. return this.lights[index];
  24501. }
  24502. }
  24503. return null;
  24504. };
  24505. /**
  24506. * Gets a particle system by id
  24507. * @param id defines the particle system id
  24508. * @return the corresponding system or null if none found
  24509. */
  24510. Scene.prototype.getParticleSystemByID = function (id) {
  24511. for (var index = 0; index < this.particleSystems.length; index++) {
  24512. if (this.particleSystems[index].id === id) {
  24513. return this.particleSystems[index];
  24514. }
  24515. }
  24516. return null;
  24517. };
  24518. /**
  24519. * Gets a geometry using its ID
  24520. * @param id defines the geometry's id
  24521. * @return the geometry or null if none found.
  24522. */
  24523. Scene.prototype.getGeometryByID = function (id) {
  24524. for (var index = 0; index < this._geometries.length; index++) {
  24525. if (this._geometries[index].id === id) {
  24526. return this._geometries[index];
  24527. }
  24528. }
  24529. return null;
  24530. };
  24531. /**
  24532. * Add a new geometry to this scene
  24533. * @param geometry defines the geometry to be added to the scene.
  24534. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  24535. * @return a boolean defining if the geometry was added or not
  24536. */
  24537. Scene.prototype.pushGeometry = function (geometry, force) {
  24538. if (!force && this.getGeometryByID(geometry.id)) {
  24539. return false;
  24540. }
  24541. this._geometries.push(geometry);
  24542. //notify the collision coordinator
  24543. if (this.collisionCoordinator) {
  24544. this.collisionCoordinator.onGeometryAdded(geometry);
  24545. }
  24546. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24547. return true;
  24548. };
  24549. /**
  24550. * Removes an existing geometry
  24551. * @param geometry defines the geometry to be removed from the scene
  24552. * @return a boolean defining if the geometry was removed or not
  24553. */
  24554. Scene.prototype.removeGeometry = function (geometry) {
  24555. var index = this._geometries.indexOf(geometry);
  24556. if (index > -1) {
  24557. this._geometries.splice(index, 1);
  24558. //notify the collision coordinator
  24559. if (this.collisionCoordinator) {
  24560. this.collisionCoordinator.onGeometryDeleted(geometry);
  24561. }
  24562. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24563. return true;
  24564. }
  24565. return false;
  24566. };
  24567. /**
  24568. * Gets the list of geometries attached to the scene
  24569. * @returns an array of Geometry
  24570. */
  24571. Scene.prototype.getGeometries = function () {
  24572. return this._geometries;
  24573. };
  24574. /**
  24575. * Gets the first added mesh found of a given ID
  24576. * @param id defines the id to search for
  24577. * @return the mesh found or null if not found at all
  24578. */
  24579. Scene.prototype.getMeshByID = function (id) {
  24580. for (var index = 0; index < this.meshes.length; index++) {
  24581. if (this.meshes[index].id === id) {
  24582. return this.meshes[index];
  24583. }
  24584. }
  24585. return null;
  24586. };
  24587. /**
  24588. * Gets a list of meshes using their id
  24589. * @param id defines the id to search for
  24590. * @returns a list of meshes
  24591. */
  24592. Scene.prototype.getMeshesByID = function (id) {
  24593. return this.meshes.filter(function (m) {
  24594. return m.id === id;
  24595. });
  24596. };
  24597. /**
  24598. * Gets the first added transform node found of a given ID
  24599. * @param id defines the id to search for
  24600. * @return the found transform node or null if not found at all.
  24601. */
  24602. Scene.prototype.getTransformNodeByID = function (id) {
  24603. for (var index = 0; index < this.transformNodes.length; index++) {
  24604. if (this.transformNodes[index].id === id) {
  24605. return this.transformNodes[index];
  24606. }
  24607. }
  24608. return null;
  24609. };
  24610. /**
  24611. * Gets a list of transform nodes using their id
  24612. * @param id defines the id to search for
  24613. * @returns a list of transform nodes
  24614. */
  24615. Scene.prototype.getTransformNodesByID = function (id) {
  24616. return this.transformNodes.filter(function (m) {
  24617. return m.id === id;
  24618. });
  24619. };
  24620. /**
  24621. * Gets a mesh with its auto-generated unique id
  24622. * @param uniqueId defines the unique id to search for
  24623. * @return the found mesh or null if not found at all.
  24624. */
  24625. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24626. for (var index = 0; index < this.meshes.length; index++) {
  24627. if (this.meshes[index].uniqueId === uniqueId) {
  24628. return this.meshes[index];
  24629. }
  24630. }
  24631. return null;
  24632. };
  24633. /**
  24634. * Gets a the last added mesh using a given id
  24635. * @param id defines the id to search for
  24636. * @return the found mesh or null if not found at all.
  24637. */
  24638. Scene.prototype.getLastMeshByID = function (id) {
  24639. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24640. if (this.meshes[index].id === id) {
  24641. return this.meshes[index];
  24642. }
  24643. }
  24644. return null;
  24645. };
  24646. /**
  24647. * Gets a the last added node (Mesh, Camera, Light) using a given id
  24648. * @param id defines the id to search for
  24649. * @return the found node or null if not found at all
  24650. */
  24651. Scene.prototype.getLastEntryByID = function (id) {
  24652. var index;
  24653. for (index = this.meshes.length - 1; index >= 0; index--) {
  24654. if (this.meshes[index].id === id) {
  24655. return this.meshes[index];
  24656. }
  24657. }
  24658. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24659. if (this.transformNodes[index].id === id) {
  24660. return this.transformNodes[index];
  24661. }
  24662. }
  24663. for (index = this.cameras.length - 1; index >= 0; index--) {
  24664. if (this.cameras[index].id === id) {
  24665. return this.cameras[index];
  24666. }
  24667. }
  24668. for (index = this.lights.length - 1; index >= 0; index--) {
  24669. if (this.lights[index].id === id) {
  24670. return this.lights[index];
  24671. }
  24672. }
  24673. return null;
  24674. };
  24675. /**
  24676. * Gets a node (Mesh, Camera, Light) using a given id
  24677. * @param id defines the id to search for
  24678. * @return the found node or null if not found at all
  24679. */
  24680. Scene.prototype.getNodeByID = function (id) {
  24681. var mesh = this.getMeshByID(id);
  24682. if (mesh) {
  24683. return mesh;
  24684. }
  24685. var light = this.getLightByID(id);
  24686. if (light) {
  24687. return light;
  24688. }
  24689. var camera = this.getCameraByID(id);
  24690. if (camera) {
  24691. return camera;
  24692. }
  24693. var bone = this.getBoneByID(id);
  24694. return bone;
  24695. };
  24696. /**
  24697. * Gets a node (Mesh, Camera, Light) using a given name
  24698. * @param name defines the name to search for
  24699. * @return the found node or null if not found at all.
  24700. */
  24701. Scene.prototype.getNodeByName = function (name) {
  24702. var mesh = this.getMeshByName(name);
  24703. if (mesh) {
  24704. return mesh;
  24705. }
  24706. var light = this.getLightByName(name);
  24707. if (light) {
  24708. return light;
  24709. }
  24710. var camera = this.getCameraByName(name);
  24711. if (camera) {
  24712. return camera;
  24713. }
  24714. var bone = this.getBoneByName(name);
  24715. return bone;
  24716. };
  24717. /**
  24718. * Gets a mesh using a given name
  24719. * @param name defines the name to search for
  24720. * @return the found mesh or null if not found at all.
  24721. */
  24722. Scene.prototype.getMeshByName = function (name) {
  24723. for (var index = 0; index < this.meshes.length; index++) {
  24724. if (this.meshes[index].name === name) {
  24725. return this.meshes[index];
  24726. }
  24727. }
  24728. return null;
  24729. };
  24730. /**
  24731. * Gets a transform node using a given name
  24732. * @param name defines the name to search for
  24733. * @return the found transform node or null if not found at all.
  24734. */
  24735. Scene.prototype.getTransformNodeByName = function (name) {
  24736. for (var index = 0; index < this.transformNodes.length; index++) {
  24737. if (this.transformNodes[index].name === name) {
  24738. return this.transformNodes[index];
  24739. }
  24740. }
  24741. return null;
  24742. };
  24743. /**
  24744. * Gets a sound using a given name
  24745. * @param name defines the name to search for
  24746. * @return the found sound or null if not found at all.
  24747. */
  24748. Scene.prototype.getSoundByName = function (name) {
  24749. var index;
  24750. if (BABYLON.AudioEngine) {
  24751. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24752. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24753. return this.mainSoundTrack.soundCollection[index];
  24754. }
  24755. }
  24756. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24757. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24758. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24759. return this.soundTracks[sdIndex].soundCollection[index];
  24760. }
  24761. }
  24762. }
  24763. }
  24764. return null;
  24765. };
  24766. /**
  24767. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  24768. * @param id defines the id to search for
  24769. * @return the found skeleton or null if not found at all.
  24770. */
  24771. Scene.prototype.getLastSkeletonByID = function (id) {
  24772. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24773. if (this.skeletons[index].id === id) {
  24774. return this.skeletons[index];
  24775. }
  24776. }
  24777. return null;
  24778. };
  24779. /**
  24780. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  24781. * @param id defines the id to search for
  24782. * @return the found skeleton or null if not found at all.
  24783. */
  24784. Scene.prototype.getSkeletonById = function (id) {
  24785. for (var index = 0; index < this.skeletons.length; index++) {
  24786. if (this.skeletons[index].id === id) {
  24787. return this.skeletons[index];
  24788. }
  24789. }
  24790. return null;
  24791. };
  24792. /**
  24793. * Gets a skeleton using a given name
  24794. * @param name defines the name to search for
  24795. * @return the found skeleton or null if not found at all.
  24796. */
  24797. Scene.prototype.getSkeletonByName = function (name) {
  24798. for (var index = 0; index < this.skeletons.length; index++) {
  24799. if (this.skeletons[index].name === name) {
  24800. return this.skeletons[index];
  24801. }
  24802. }
  24803. return null;
  24804. };
  24805. /**
  24806. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  24807. * @param id defines the id to search for
  24808. * @return the found morph target manager or null if not found at all.
  24809. */
  24810. Scene.prototype.getMorphTargetManagerById = function (id) {
  24811. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24812. if (this.morphTargetManagers[index].uniqueId === id) {
  24813. return this.morphTargetManagers[index];
  24814. }
  24815. }
  24816. return null;
  24817. };
  24818. /**
  24819. * Gets a boolean indicating if the given mesh is active
  24820. * @param mesh defines the mesh to look for
  24821. * @returns true if the mesh is in the active list
  24822. */
  24823. Scene.prototype.isActiveMesh = function (mesh) {
  24824. return (this._activeMeshes.indexOf(mesh) !== -1);
  24825. };
  24826. /**
  24827. * Return a the first highlight layer of the scene with a given name.
  24828. * @param name The name of the highlight layer to look for.
  24829. * @return The highlight layer if found otherwise null.
  24830. */
  24831. Scene.prototype.getHighlightLayerByName = function (name) {
  24832. for (var index = 0; index < this.effectLayers.length; index++) {
  24833. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24834. return this.effectLayers[index];
  24835. }
  24836. }
  24837. return null;
  24838. };
  24839. /**
  24840. * Return a the first highlight layer of the scene with a given name.
  24841. * @param name The name of the highlight layer to look for.
  24842. * @return The highlight layer if found otherwise null.
  24843. */
  24844. Scene.prototype.getGlowLayerByName = function (name) {
  24845. for (var index = 0; index < this.effectLayers.length; index++) {
  24846. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24847. return this.effectLayers[index];
  24848. }
  24849. }
  24850. return null;
  24851. };
  24852. Object.defineProperty(Scene.prototype, "uid", {
  24853. /**
  24854. * Return a unique id as a string which can serve as an identifier for the scene
  24855. */
  24856. get: function () {
  24857. if (!this._uid) {
  24858. this._uid = BABYLON.Tools.RandomId();
  24859. }
  24860. return this._uid;
  24861. },
  24862. enumerable: true,
  24863. configurable: true
  24864. });
  24865. /**
  24866. * Add an externaly attached data from its key.
  24867. * This method call will fail and return false, if such key already exists.
  24868. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24869. * @param key the unique key that identifies the data
  24870. * @param data the data object to associate to the key for this Engine instance
  24871. * @return true if no such key were already present and the data was added successfully, false otherwise
  24872. */
  24873. Scene.prototype.addExternalData = function (key, data) {
  24874. if (!this._externalData) {
  24875. this._externalData = new BABYLON.StringDictionary();
  24876. }
  24877. return this._externalData.add(key, data);
  24878. };
  24879. /**
  24880. * Get an externaly attached data from its key
  24881. * @param key the unique key that identifies the data
  24882. * @return the associated data, if present (can be null), or undefined if not present
  24883. */
  24884. Scene.prototype.getExternalData = function (key) {
  24885. if (!this._externalData) {
  24886. return null;
  24887. }
  24888. return this._externalData.get(key);
  24889. };
  24890. /**
  24891. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24892. * @param key the unique key that identifies the data
  24893. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24894. * @return the associated data, can be null if the factory returned null.
  24895. */
  24896. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24897. if (!this._externalData) {
  24898. this._externalData = new BABYLON.StringDictionary();
  24899. }
  24900. return this._externalData.getOrAddWithFactory(key, factory);
  24901. };
  24902. /**
  24903. * Remove an externaly attached data from the Engine instance
  24904. * @param key the unique key that identifies the data
  24905. * @return true if the data was successfully removed, false if it doesn't exist
  24906. */
  24907. Scene.prototype.removeExternalData = function (key) {
  24908. return this._externalData.remove(key);
  24909. };
  24910. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24911. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24912. if (mesh.showSubMeshesBoundingBox) {
  24913. var boundingInfo = subMesh.getBoundingInfo();
  24914. if (boundingInfo !== null && boundingInfo !== undefined) {
  24915. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24916. }
  24917. }
  24918. var material = subMesh.getMaterial();
  24919. if (material !== null && material !== undefined) {
  24920. // Render targets
  24921. if (material.getRenderTargetTextures !== undefined) {
  24922. if (this._processedMaterials.indexOf(material) === -1) {
  24923. this._processedMaterials.push(material);
  24924. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24925. }
  24926. }
  24927. // Dispatch
  24928. this._activeIndices.addCount(subMesh.indexCount, false);
  24929. this._renderingManager.dispatch(subMesh, mesh, material);
  24930. }
  24931. }
  24932. };
  24933. /**
  24934. * Clear the processed materials smart array preventing retention point in material dispose.
  24935. */
  24936. Scene.prototype.freeProcessedMaterials = function () {
  24937. this._processedMaterials.dispose();
  24938. };
  24939. /**
  24940. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24941. */
  24942. Scene.prototype.freeActiveMeshes = function () {
  24943. this._activeMeshes.dispose();
  24944. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24945. this.activeCamera._activeMeshes.dispose();
  24946. }
  24947. if (this.activeCameras) {
  24948. for (var i = 0; i < this.activeCameras.length; i++) {
  24949. var activeCamera = this.activeCameras[i];
  24950. if (activeCamera && activeCamera._activeMeshes) {
  24951. activeCamera._activeMeshes.dispose();
  24952. }
  24953. }
  24954. }
  24955. };
  24956. /**
  24957. * Clear the info related to rendering groups preventing retention points during dispose.
  24958. */
  24959. Scene.prototype.freeRenderingGroups = function () {
  24960. if (this._renderingManager) {
  24961. this._renderingManager.freeRenderingGroups();
  24962. }
  24963. if (this.textures) {
  24964. for (var i = 0; i < this.textures.length; i++) {
  24965. var texture = this.textures[i];
  24966. if (texture && texture.renderList) {
  24967. texture.freeRenderingGroups();
  24968. }
  24969. }
  24970. }
  24971. };
  24972. /** @ignore */
  24973. Scene.prototype._isInIntermediateRendering = function () {
  24974. return this._intermediateRendering;
  24975. };
  24976. /**
  24977. * Defines the current active mesh candidate provider
  24978. * @param provider defines the provider to use
  24979. */
  24980. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24981. this._activeMeshCandidateProvider = provider;
  24982. };
  24983. /**
  24984. * Gets the current active mesh candidate provider
  24985. * @returns the current active mesh candidate provider
  24986. */
  24987. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24988. return this._activeMeshCandidateProvider;
  24989. };
  24990. /**
  24991. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24992. * @returns the current scene
  24993. */
  24994. Scene.prototype.freezeActiveMeshes = function () {
  24995. if (!this.activeCamera) {
  24996. return this;
  24997. }
  24998. if (!this._frustumPlanes) {
  24999. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  25000. }
  25001. this._evaluateActiveMeshes();
  25002. this._activeMeshesFrozen = true;
  25003. return this;
  25004. };
  25005. /**
  25006. * Use this function to restart evaluating active meshes on every frame
  25007. * @returns the current scene
  25008. */
  25009. Scene.prototype.unfreezeActiveMeshes = function () {
  25010. this._activeMeshesFrozen = false;
  25011. return this;
  25012. };
  25013. Scene.prototype._evaluateActiveMeshes = function () {
  25014. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  25015. return;
  25016. }
  25017. if (!this.activeCamera) {
  25018. return;
  25019. }
  25020. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  25021. this.activeCamera._activeMeshes.reset();
  25022. this._activeMeshes.reset();
  25023. this._renderingManager.reset();
  25024. this._processedMaterials.reset();
  25025. this._activeParticleSystems.reset();
  25026. this._activeSkeletons.reset();
  25027. this._softwareSkinnedMeshes.reset();
  25028. if (this._boundingBoxRenderer) {
  25029. this._boundingBoxRenderer.reset();
  25030. }
  25031. // Meshes
  25032. var meshes;
  25033. var len;
  25034. var checkIsEnabled = true;
  25035. // Determine mesh candidates
  25036. if (this._activeMeshCandidateProvider !== undefined) {
  25037. // Use _activeMeshCandidateProvider
  25038. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  25039. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  25040. if (meshes !== undefined) {
  25041. len = meshes.length;
  25042. }
  25043. else {
  25044. len = 0;
  25045. }
  25046. }
  25047. else if (this._selectionOctree !== undefined) {
  25048. // Octree
  25049. var selection = this._selectionOctree.select(this._frustumPlanes);
  25050. meshes = selection.data;
  25051. len = selection.length;
  25052. }
  25053. else {
  25054. // Full scene traversal
  25055. len = this.meshes.length;
  25056. meshes = this.meshes;
  25057. }
  25058. // Check each mesh
  25059. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  25060. mesh = meshes[meshIndex];
  25061. if (mesh.isBlocked) {
  25062. continue;
  25063. }
  25064. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  25065. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  25066. continue;
  25067. }
  25068. mesh.computeWorldMatrix();
  25069. // Intersections
  25070. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  25071. this._meshesForIntersections.pushNoDuplicate(mesh);
  25072. }
  25073. // Switch to current LOD
  25074. meshLOD = mesh.getLOD(this.activeCamera);
  25075. if (meshLOD === undefined || meshLOD === null) {
  25076. continue;
  25077. }
  25078. mesh._preActivate();
  25079. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  25080. this._activeMeshes.push(mesh);
  25081. this.activeCamera._activeMeshes.push(mesh);
  25082. mesh._activate(this._renderId);
  25083. if (meshLOD !== mesh) {
  25084. meshLOD._activate(this._renderId);
  25085. }
  25086. this._activeMesh(mesh, meshLOD);
  25087. }
  25088. }
  25089. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  25090. // Particle systems
  25091. if (this.particlesEnabled) {
  25092. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  25093. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  25094. var particleSystem = this.particleSystems[particleIndex];
  25095. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  25096. continue;
  25097. }
  25098. var emitter = particleSystem.emitter;
  25099. if (!emitter.position || emitter.isEnabled()) {
  25100. this._activeParticleSystems.push(particleSystem);
  25101. particleSystem.animate();
  25102. this._renderingManager.dispatchParticles(particleSystem);
  25103. }
  25104. }
  25105. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  25106. }
  25107. };
  25108. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  25109. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  25110. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  25111. mesh.skeleton.prepare();
  25112. }
  25113. if (!mesh.computeBonesUsingShaders) {
  25114. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  25115. }
  25116. }
  25117. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  25118. var boundingInfo = sourceMesh.getBoundingInfo();
  25119. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  25120. }
  25121. if (mesh !== undefined && mesh !== null
  25122. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  25123. // Submeshes Octrees
  25124. var len;
  25125. var subMeshes;
  25126. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  25127. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  25128. len = intersections.length;
  25129. subMeshes = intersections.data;
  25130. }
  25131. else {
  25132. subMeshes = mesh.subMeshes;
  25133. len = subMeshes.length;
  25134. }
  25135. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  25136. subMesh = subMeshes[subIndex];
  25137. this._evaluateSubMesh(subMesh, mesh);
  25138. }
  25139. }
  25140. };
  25141. /**
  25142. * Update the transform matrix to update from the current active camera
  25143. * @param force defines a boolean used to force the update even if cache is up to date
  25144. */
  25145. Scene.prototype.updateTransformMatrix = function (force) {
  25146. if (!this.activeCamera) {
  25147. return;
  25148. }
  25149. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  25150. };
  25151. /**
  25152. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  25153. * @param alternateCamera defines the camera to use
  25154. */
  25155. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  25156. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  25157. };
  25158. Scene.prototype._renderForCamera = function (camera, rigParent) {
  25159. if (camera && camera._skipRendering) {
  25160. return;
  25161. }
  25162. var engine = this._engine;
  25163. this.activeCamera = camera;
  25164. if (!this.activeCamera)
  25165. throw new Error("Active camera not set");
  25166. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  25167. // Viewport
  25168. engine.setViewport(this.activeCamera.viewport);
  25169. // Camera
  25170. this.resetCachedMaterial();
  25171. this._renderId++;
  25172. this.updateTransformMatrix();
  25173. if (camera._alternateCamera) {
  25174. this.updateAlternateTransformMatrix(camera._alternateCamera);
  25175. this._alternateRendering = true;
  25176. }
  25177. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  25178. // Meshes
  25179. this._evaluateActiveMeshes();
  25180. // Software skinning
  25181. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  25182. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  25183. mesh.applySkeleton(mesh.skeleton);
  25184. }
  25185. // Render targets
  25186. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  25187. var needsRestoreFrameBuffer = false;
  25188. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  25189. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  25190. }
  25191. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  25192. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  25193. }
  25194. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  25195. this._intermediateRendering = true;
  25196. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  25197. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  25198. var renderTarget = this._renderTargets.data[renderIndex];
  25199. if (renderTarget._shouldRender()) {
  25200. this._renderId++;
  25201. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  25202. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  25203. }
  25204. }
  25205. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  25206. this._intermediateRendering = false;
  25207. this._renderId++;
  25208. needsRestoreFrameBuffer = true; // Restore back buffer
  25209. }
  25210. // Render EffecttLayer Texture
  25211. var stencilState = this._engine.getStencilBuffer();
  25212. var renderEffects = false;
  25213. var needStencil = false;
  25214. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  25215. this._intermediateRendering = true;
  25216. for (var i = 0; i < this.effectLayers.length; i++) {
  25217. var effectLayer = this.effectLayers[i];
  25218. if (effectLayer.shouldRender() &&
  25219. (!effectLayer.camera ||
  25220. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  25221. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  25222. renderEffects = true;
  25223. needStencil = needStencil || effectLayer.needStencil();
  25224. var renderTarget = effectLayer._mainTexture;
  25225. if (renderTarget._shouldRender()) {
  25226. this._renderId++;
  25227. renderTarget.render(false, false);
  25228. needsRestoreFrameBuffer = true;
  25229. }
  25230. }
  25231. }
  25232. this._intermediateRendering = false;
  25233. this._renderId++;
  25234. }
  25235. if (needsRestoreFrameBuffer) {
  25236. engine.restoreDefaultFramebuffer(); // Restore back buffer
  25237. }
  25238. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  25239. // Prepare Frame
  25240. this.postProcessManager._prepareFrame();
  25241. // Backgrounds
  25242. var layerIndex;
  25243. var layer;
  25244. if (this.layers.length) {
  25245. engine.setDepthBuffer(false);
  25246. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  25247. layer = this.layers[layerIndex];
  25248. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  25249. layer.render();
  25250. }
  25251. }
  25252. engine.setDepthBuffer(true);
  25253. }
  25254. // Activate effect Layer stencil
  25255. if (needStencil) {
  25256. this._engine.setStencilBuffer(true);
  25257. }
  25258. // Render
  25259. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  25260. this._renderingManager.render(null, null, true, true);
  25261. this.onAfterDrawPhaseObservable.notifyObservers(this);
  25262. // Restore effect Layer stencil
  25263. if (needStencil) {
  25264. this._engine.setStencilBuffer(stencilState);
  25265. }
  25266. // Bounding boxes
  25267. if (this._boundingBoxRenderer) {
  25268. this._boundingBoxRenderer.render();
  25269. }
  25270. // Lens flares
  25271. if (this.lensFlaresEnabled) {
  25272. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  25273. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  25274. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  25275. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  25276. lensFlareSystem.render();
  25277. }
  25278. }
  25279. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  25280. }
  25281. // Effect Layer
  25282. if (renderEffects) {
  25283. engine.setDepthBuffer(false);
  25284. for (var i = 0; i < this.effectLayers.length; i++) {
  25285. if (this.effectLayers[i].shouldRender()) {
  25286. this.effectLayers[i].render();
  25287. }
  25288. }
  25289. engine.setDepthBuffer(true);
  25290. }
  25291. // Foregrounds
  25292. if (this.layers.length) {
  25293. engine.setDepthBuffer(false);
  25294. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  25295. layer = this.layers[layerIndex];
  25296. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  25297. layer.render();
  25298. }
  25299. }
  25300. engine.setDepthBuffer(true);
  25301. }
  25302. // Finalize frame
  25303. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  25304. // Reset some special arrays
  25305. this._renderTargets.reset();
  25306. this._alternateRendering = false;
  25307. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  25308. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  25309. };
  25310. Scene.prototype._processSubCameras = function (camera) {
  25311. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  25312. this._renderForCamera(camera);
  25313. return;
  25314. }
  25315. // rig cameras
  25316. for (var index = 0; index < camera._rigCameras.length; index++) {
  25317. this._renderForCamera(camera._rigCameras[index], camera);
  25318. }
  25319. this.activeCamera = camera;
  25320. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  25321. };
  25322. Scene.prototype._checkIntersections = function () {
  25323. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  25324. var sourceMesh = this._meshesForIntersections.data[index];
  25325. if (!sourceMesh.actionManager) {
  25326. continue;
  25327. }
  25328. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  25329. var action = sourceMesh.actionManager.actions[actionIndex];
  25330. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  25331. var parameters = action.getTriggerParameter();
  25332. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  25333. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  25334. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  25335. if (areIntersecting && currentIntersectionInProgress === -1) {
  25336. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  25337. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  25338. sourceMesh._intersectionsInProgress.push(otherMesh);
  25339. }
  25340. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  25341. sourceMesh._intersectionsInProgress.push(otherMesh);
  25342. }
  25343. }
  25344. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  25345. //They intersected, and now they don't.
  25346. //is this trigger an exit trigger? execute an event.
  25347. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  25348. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  25349. }
  25350. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  25351. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  25352. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  25353. }
  25354. }
  25355. }
  25356. }
  25357. }
  25358. };
  25359. /**
  25360. * Render the scene
  25361. */
  25362. Scene.prototype.render = function () {
  25363. if (this.isDisposed) {
  25364. return;
  25365. }
  25366. this._activeParticles.fetchNewFrame();
  25367. this._totalVertices.fetchNewFrame();
  25368. this._activeIndices.fetchNewFrame();
  25369. this._activeBones.fetchNewFrame();
  25370. this._meshesForIntersections.reset();
  25371. this.resetCachedMaterial();
  25372. this.onBeforeAnimationsObservable.notifyObservers(this);
  25373. // Actions
  25374. if (this.actionManager) {
  25375. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  25376. }
  25377. //Simplification Queue
  25378. if (this.simplificationQueue && !this.simplificationQueue.running) {
  25379. this.simplificationQueue.executeNext();
  25380. }
  25381. if (this._engine.isDeterministicLockStep()) {
  25382. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  25383. var defaultFPS = (60.0 / 1000.0);
  25384. var defaultFrameTime = 1000 / 60; // frame time in MS
  25385. if (this._physicsEngine) {
  25386. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  25387. }
  25388. var stepsTaken = 0;
  25389. var maxSubSteps = this._engine.getLockstepMaxSteps();
  25390. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  25391. internalSteps = Math.min(internalSteps, maxSubSteps);
  25392. do {
  25393. this.onBeforeStepObservable.notifyObservers(this);
  25394. // Animations
  25395. this._animationRatio = defaultFrameTime * defaultFPS;
  25396. this._animate();
  25397. this.onAfterAnimationsObservable.notifyObservers(this);
  25398. // Physics
  25399. if (this._physicsEngine) {
  25400. this.onBeforePhysicsObservable.notifyObservers(this);
  25401. this._physicsEngine._step(defaultFrameTime / 1000);
  25402. this.onAfterPhysicsObservable.notifyObservers(this);
  25403. }
  25404. this.onAfterStepObservable.notifyObservers(this);
  25405. this._currentStepId++;
  25406. stepsTaken++;
  25407. deltaTime -= defaultFrameTime;
  25408. } while (deltaTime > 0 && stepsTaken < internalSteps);
  25409. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  25410. }
  25411. else {
  25412. // Animations
  25413. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  25414. this._animationRatio = deltaTime * (60.0 / 1000.0);
  25415. this._animate();
  25416. this.onAfterAnimationsObservable.notifyObservers(this);
  25417. // Physics
  25418. if (this._physicsEngine) {
  25419. this.onBeforePhysicsObservable.notifyObservers(this);
  25420. this._physicsEngine._step(deltaTime / 1000.0);
  25421. this.onAfterPhysicsObservable.notifyObservers(this);
  25422. }
  25423. }
  25424. // update gamepad manager
  25425. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  25426. this._gamepadManager._checkGamepadsStatus();
  25427. }
  25428. // Update Cameras
  25429. if (this.activeCameras.length > 0) {
  25430. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  25431. var camera = this.activeCameras[cameraIndex];
  25432. camera.update();
  25433. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  25434. // rig cameras
  25435. for (var index = 0; index < camera._rigCameras.length; index++) {
  25436. camera._rigCameras[index].update();
  25437. }
  25438. }
  25439. }
  25440. }
  25441. else if (this.activeCamera) {
  25442. this.activeCamera.update();
  25443. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  25444. // rig cameras
  25445. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  25446. this.activeCamera._rigCameras[index].update();
  25447. }
  25448. }
  25449. }
  25450. // Before render
  25451. this.onBeforeRenderObservable.notifyObservers(this);
  25452. // Customs render targets
  25453. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  25454. var engine = this.getEngine();
  25455. var currentActiveCamera = this.activeCamera;
  25456. if (this.renderTargetsEnabled) {
  25457. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  25458. this._intermediateRendering = true;
  25459. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  25460. var renderTarget = this.customRenderTargets[customIndex];
  25461. if (renderTarget._shouldRender()) {
  25462. this._renderId++;
  25463. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  25464. if (!this.activeCamera)
  25465. throw new Error("Active camera not set");
  25466. // Viewport
  25467. engine.setViewport(this.activeCamera.viewport);
  25468. // Camera
  25469. this.updateTransformMatrix();
  25470. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  25471. }
  25472. }
  25473. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  25474. this._intermediateRendering = false;
  25475. this._renderId++;
  25476. }
  25477. // Restore back buffer
  25478. if (this.customRenderTargets.length > 0) {
  25479. engine.restoreDefaultFramebuffer();
  25480. }
  25481. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  25482. this.activeCamera = currentActiveCamera;
  25483. // Procedural textures
  25484. if (this.proceduralTexturesEnabled) {
  25485. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  25486. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  25487. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  25488. if (proceduralTexture._shouldRender()) {
  25489. proceduralTexture.render();
  25490. }
  25491. }
  25492. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  25493. }
  25494. // Clear
  25495. if (this.autoClearDepthAndStencil || this.autoClear) {
  25496. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  25497. }
  25498. // Shadows
  25499. if (this.shadowsEnabled) {
  25500. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  25501. var light = this.lights[lightIndex];
  25502. var shadowGenerator = light.getShadowGenerator();
  25503. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  25504. var shadowMap = (shadowGenerator.getShadowMap());
  25505. if (this.textures.indexOf(shadowMap) !== -1) {
  25506. this._renderTargets.push(shadowMap);
  25507. }
  25508. }
  25509. }
  25510. }
  25511. // Depth renderer
  25512. for (var key in this._depthRenderer) {
  25513. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  25514. }
  25515. // Geometry renderer
  25516. if (this._geometryBufferRenderer) {
  25517. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  25518. }
  25519. // RenderPipeline
  25520. if (this._postProcessRenderPipelineManager) {
  25521. this._postProcessRenderPipelineManager.update();
  25522. }
  25523. // Multi-cameras?
  25524. if (this.activeCameras.length > 0) {
  25525. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  25526. if (cameraIndex > 0) {
  25527. this._engine.clear(null, false, true, true);
  25528. }
  25529. this._processSubCameras(this.activeCameras[cameraIndex]);
  25530. }
  25531. }
  25532. else {
  25533. if (!this.activeCamera) {
  25534. throw new Error("No camera defined");
  25535. }
  25536. this._processSubCameras(this.activeCamera);
  25537. }
  25538. // Intersection checks
  25539. this._checkIntersections();
  25540. // Update the audio listener attached to the camera
  25541. if (BABYLON.AudioEngine) {
  25542. this._updateAudioParameters();
  25543. }
  25544. // After render
  25545. if (this.afterRender) {
  25546. this.afterRender();
  25547. }
  25548. this.onAfterRenderObservable.notifyObservers(this);
  25549. // Cleaning
  25550. for (var index = 0; index < this._toBeDisposed.length; index++) {
  25551. var data = this._toBeDisposed.data[index];
  25552. if (data) {
  25553. data.dispose();
  25554. }
  25555. this._toBeDisposed[index] = null;
  25556. }
  25557. this._toBeDisposed.reset();
  25558. if (this.dumpNextRenderTargets) {
  25559. this.dumpNextRenderTargets = false;
  25560. }
  25561. this._activeBones.addCount(0, true);
  25562. this._activeIndices.addCount(0, true);
  25563. this._activeParticles.addCount(0, true);
  25564. };
  25565. Scene.prototype._updateAudioParameters = function () {
  25566. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  25567. return;
  25568. }
  25569. var listeningCamera;
  25570. var audioEngine = BABYLON.Engine.audioEngine;
  25571. if (this.activeCameras.length > 0) {
  25572. listeningCamera = this.activeCameras[0];
  25573. }
  25574. else {
  25575. listeningCamera = this.activeCamera;
  25576. }
  25577. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  25578. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  25579. // for VR cameras
  25580. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  25581. listeningCamera = listeningCamera.rigCameras[0];
  25582. }
  25583. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  25584. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  25585. cameraDirection.normalize();
  25586. // To avoid some errors on GearVR
  25587. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  25588. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  25589. }
  25590. var i;
  25591. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25592. var sound = this.mainSoundTrack.soundCollection[i];
  25593. if (sound.useCustomAttenuation) {
  25594. sound.updateDistanceFromListener();
  25595. }
  25596. }
  25597. for (i = 0; i < this.soundTracks.length; i++) {
  25598. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25599. sound = this.soundTracks[i].soundCollection[j];
  25600. if (sound.useCustomAttenuation) {
  25601. sound.updateDistanceFromListener();
  25602. }
  25603. }
  25604. }
  25605. }
  25606. };
  25607. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25608. // Audio
  25609. /**
  25610. * Gets or sets if audio support is enabled
  25611. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  25612. */
  25613. get: function () {
  25614. return this._audioEnabled;
  25615. },
  25616. set: function (value) {
  25617. this._audioEnabled = value;
  25618. if (BABYLON.AudioEngine) {
  25619. if (this._audioEnabled) {
  25620. this._enableAudio();
  25621. }
  25622. else {
  25623. this._disableAudio();
  25624. }
  25625. }
  25626. },
  25627. enumerable: true,
  25628. configurable: true
  25629. });
  25630. Scene.prototype._disableAudio = function () {
  25631. var i;
  25632. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25633. this.mainSoundTrack.soundCollection[i].pause();
  25634. }
  25635. for (i = 0; i < this.soundTracks.length; i++) {
  25636. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25637. this.soundTracks[i].soundCollection[j].pause();
  25638. }
  25639. }
  25640. };
  25641. Scene.prototype._enableAudio = function () {
  25642. var i;
  25643. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25644. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25645. this.mainSoundTrack.soundCollection[i].play();
  25646. }
  25647. }
  25648. for (i = 0; i < this.soundTracks.length; i++) {
  25649. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25650. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25651. this.soundTracks[i].soundCollection[j].play();
  25652. }
  25653. }
  25654. }
  25655. };
  25656. Object.defineProperty(Scene.prototype, "headphone", {
  25657. /**
  25658. * Gets or sets if audio will be output to headphones
  25659. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  25660. */
  25661. get: function () {
  25662. return this._headphone;
  25663. },
  25664. set: function (value) {
  25665. this._headphone = value;
  25666. if (BABYLON.AudioEngine) {
  25667. if (this._headphone) {
  25668. this._switchAudioModeForHeadphones();
  25669. }
  25670. else {
  25671. this._switchAudioModeForNormalSpeakers();
  25672. }
  25673. }
  25674. },
  25675. enumerable: true,
  25676. configurable: true
  25677. });
  25678. Scene.prototype._switchAudioModeForHeadphones = function () {
  25679. this.mainSoundTrack.switchPanningModelToHRTF();
  25680. for (var i = 0; i < this.soundTracks.length; i++) {
  25681. this.soundTracks[i].switchPanningModelToHRTF();
  25682. }
  25683. };
  25684. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25685. this.mainSoundTrack.switchPanningModelToEqualPower();
  25686. for (var i = 0; i < this.soundTracks.length; i++) {
  25687. this.soundTracks[i].switchPanningModelToEqualPower();
  25688. }
  25689. };
  25690. /**
  25691. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25692. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25693. * @returns the created depth renderer
  25694. */
  25695. Scene.prototype.enableDepthRenderer = function (camera) {
  25696. camera = camera || this.activeCamera;
  25697. if (!camera) {
  25698. throw "No camera available to enable depth renderer";
  25699. }
  25700. if (!this._depthRenderer[camera.id]) {
  25701. var textureType = 0;
  25702. if (this._engine.getCaps().textureHalfFloatRender) {
  25703. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  25704. }
  25705. else if (this._engine.getCaps().textureFloatRender) {
  25706. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  25707. }
  25708. else {
  25709. throw "Depth renderer does not support int texture type";
  25710. }
  25711. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  25712. }
  25713. return this._depthRenderer[camera.id];
  25714. };
  25715. /**
  25716. * Disables a depth renderer for a given camera
  25717. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25718. */
  25719. Scene.prototype.disableDepthRenderer = function (camera) {
  25720. camera = camera || this.activeCamera;
  25721. if (!camera || !this._depthRenderer[camera.id]) {
  25722. return;
  25723. }
  25724. this._depthRenderer[camera.id].dispose();
  25725. delete this._depthRenderer[camera.id];
  25726. };
  25727. /**
  25728. * Enables a GeometryBufferRender and associates it with the scene
  25729. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  25730. * @returns the GeometryBufferRenderer
  25731. */
  25732. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25733. if (ratio === void 0) { ratio = 1; }
  25734. if (this._geometryBufferRenderer) {
  25735. return this._geometryBufferRenderer;
  25736. }
  25737. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25738. if (!this._geometryBufferRenderer.isSupported) {
  25739. this._geometryBufferRenderer = null;
  25740. }
  25741. return this._geometryBufferRenderer;
  25742. };
  25743. /**
  25744. * Disables the GeometryBufferRender associated with the scene
  25745. */
  25746. Scene.prototype.disableGeometryBufferRenderer = function () {
  25747. if (!this._geometryBufferRenderer) {
  25748. return;
  25749. }
  25750. this._geometryBufferRenderer.dispose();
  25751. this._geometryBufferRenderer = null;
  25752. };
  25753. /**
  25754. * Freeze all materials
  25755. * A frozen material will not be updatable but should be faster to render
  25756. */
  25757. Scene.prototype.freezeMaterials = function () {
  25758. for (var i = 0; i < this.materials.length; i++) {
  25759. this.materials[i].freeze();
  25760. }
  25761. };
  25762. /**
  25763. * Unfreeze all materials
  25764. * A frozen material will not be updatable but should be faster to render
  25765. */
  25766. Scene.prototype.unfreezeMaterials = function () {
  25767. for (var i = 0; i < this.materials.length; i++) {
  25768. this.materials[i].unfreeze();
  25769. }
  25770. };
  25771. /**
  25772. * Releases all held ressources
  25773. */
  25774. Scene.prototype.dispose = function () {
  25775. this.beforeRender = null;
  25776. this.afterRender = null;
  25777. this.skeletons = [];
  25778. this.morphTargetManagers = [];
  25779. this.importedMeshesFiles = new Array();
  25780. this.stopAllAnimations();
  25781. this.resetCachedMaterial();
  25782. for (var key in this._depthRenderer) {
  25783. this._depthRenderer[key].dispose();
  25784. }
  25785. if (this._gamepadManager) {
  25786. this._gamepadManager.dispose();
  25787. this._gamepadManager = null;
  25788. }
  25789. // Smart arrays
  25790. if (this.activeCamera) {
  25791. this.activeCamera._activeMeshes.dispose();
  25792. this.activeCamera = null;
  25793. }
  25794. this._activeMeshes.dispose();
  25795. this._renderingManager.dispose();
  25796. this._processedMaterials.dispose();
  25797. this._activeParticleSystems.dispose();
  25798. this._activeSkeletons.dispose();
  25799. this._softwareSkinnedMeshes.dispose();
  25800. this._renderTargets.dispose();
  25801. this._registeredForLateAnimationBindings.dispose();
  25802. if (this._boundingBoxRenderer) {
  25803. this._boundingBoxRenderer.dispose();
  25804. }
  25805. this._meshesForIntersections.dispose();
  25806. this._toBeDisposed.dispose();
  25807. // Abort active requests
  25808. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25809. var request = _a[_i];
  25810. request.abort();
  25811. }
  25812. // Debug layer
  25813. if (this._debugLayer) {
  25814. this._debugLayer.hide();
  25815. }
  25816. // Events
  25817. this.onDisposeObservable.notifyObservers(this);
  25818. this.onDisposeObservable.clear();
  25819. this.onBeforeRenderObservable.clear();
  25820. this.onAfterRenderObservable.clear();
  25821. this.onBeforeRenderTargetsRenderObservable.clear();
  25822. this.onAfterRenderTargetsRenderObservable.clear();
  25823. this.onAfterStepObservable.clear();
  25824. this.onBeforeStepObservable.clear();
  25825. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25826. this.onAfterActiveMeshesEvaluationObservable.clear();
  25827. this.onBeforeParticlesRenderingObservable.clear();
  25828. this.onAfterParticlesRenderingObservable.clear();
  25829. this.onBeforeSpritesRenderingObservable.clear();
  25830. this.onAfterSpritesRenderingObservable.clear();
  25831. this.onBeforeDrawPhaseObservable.clear();
  25832. this.onAfterDrawPhaseObservable.clear();
  25833. this.onBeforePhysicsObservable.clear();
  25834. this.onAfterPhysicsObservable.clear();
  25835. this.onBeforeAnimationsObservable.clear();
  25836. this.onAfterAnimationsObservable.clear();
  25837. this.onDataLoadedObservable.clear();
  25838. this.detachControl();
  25839. // Release sounds & sounds tracks
  25840. if (BABYLON.AudioEngine) {
  25841. this.disposeSounds();
  25842. }
  25843. // VR Helper
  25844. if (this.VRHelper) {
  25845. this.VRHelper.dispose();
  25846. }
  25847. // Detach cameras
  25848. var canvas = this._engine.getRenderingCanvas();
  25849. if (canvas) {
  25850. var index;
  25851. for (index = 0; index < this.cameras.length; index++) {
  25852. this.cameras[index].detachControl(canvas);
  25853. }
  25854. }
  25855. // Release animation groups
  25856. while (this.animationGroups.length) {
  25857. this.animationGroups[0].dispose();
  25858. }
  25859. // Release lights
  25860. while (this.lights.length) {
  25861. this.lights[0].dispose();
  25862. }
  25863. // Release meshes
  25864. while (this.meshes.length) {
  25865. this.meshes[0].dispose(true);
  25866. }
  25867. while (this.transformNodes.length) {
  25868. this.removeTransformNode(this.transformNodes[0]);
  25869. }
  25870. // Release cameras
  25871. while (this.cameras.length) {
  25872. this.cameras[0].dispose();
  25873. }
  25874. // Release materials
  25875. if (this.defaultMaterial) {
  25876. this.defaultMaterial.dispose();
  25877. }
  25878. while (this.multiMaterials.length) {
  25879. this.multiMaterials[0].dispose();
  25880. }
  25881. while (this.materials.length) {
  25882. this.materials[0].dispose();
  25883. }
  25884. // Release particles
  25885. while (this.particleSystems.length) {
  25886. this.particleSystems[0].dispose();
  25887. }
  25888. // Release sprites
  25889. while (this.spriteManagers.length) {
  25890. this.spriteManagers[0].dispose();
  25891. }
  25892. // Release postProcesses
  25893. while (this.postProcesses.length) {
  25894. this.postProcesses[0].dispose();
  25895. }
  25896. // Release layers
  25897. while (this.layers.length) {
  25898. this.layers[0].dispose();
  25899. }
  25900. while (this.effectLayers.length) {
  25901. this.effectLayers[0].dispose();
  25902. }
  25903. // Release textures
  25904. while (this.textures.length) {
  25905. this.textures[0].dispose();
  25906. }
  25907. // Release UBO
  25908. this._sceneUbo.dispose();
  25909. if (this._alternateSceneUbo) {
  25910. this._alternateSceneUbo.dispose();
  25911. }
  25912. // Post-processes
  25913. this.postProcessManager.dispose();
  25914. if (this._postProcessRenderPipelineManager) {
  25915. this._postProcessRenderPipelineManager.dispose();
  25916. }
  25917. // Physics
  25918. if (this._physicsEngine) {
  25919. this.disablePhysicsEngine();
  25920. }
  25921. // Remove from engine
  25922. index = this._engine.scenes.indexOf(this);
  25923. if (index > -1) {
  25924. this._engine.scenes.splice(index, 1);
  25925. }
  25926. this._engine.wipeCaches(true);
  25927. this._isDisposed = true;
  25928. };
  25929. Object.defineProperty(Scene.prototype, "isDisposed", {
  25930. /**
  25931. * Gets if the scene is already disposed
  25932. */
  25933. get: function () {
  25934. return this._isDisposed;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. /**
  25940. * Releases sounds & soundtracks
  25941. */
  25942. Scene.prototype.disposeSounds = function () {
  25943. if (!this._mainSoundTrack) {
  25944. return;
  25945. }
  25946. this.mainSoundTrack.dispose();
  25947. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25948. this.soundTracks[scIndex].dispose();
  25949. }
  25950. };
  25951. // Octrees
  25952. /**
  25953. * Get the world extend vectors with an optional filter
  25954. *
  25955. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25956. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25957. */
  25958. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25959. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25960. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25961. filterPredicate = filterPredicate || (function () { return true; });
  25962. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25963. mesh.computeWorldMatrix(true);
  25964. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25965. return;
  25966. }
  25967. var boundingInfo = mesh.getBoundingInfo();
  25968. var minBox = boundingInfo.boundingBox.minimumWorld;
  25969. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25970. BABYLON.Tools.CheckExtends(minBox, min, max);
  25971. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25972. });
  25973. return {
  25974. min: min,
  25975. max: max
  25976. };
  25977. };
  25978. /**
  25979. * Creates or updates the octree used to boost selection (picking)
  25980. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25981. * @param maxCapacity defines the maximum capacity per leaf
  25982. * @param maxDepth defines the maximum depth of the octree
  25983. * @returns an octree of AbstractMesh
  25984. */
  25985. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25986. if (maxCapacity === void 0) { maxCapacity = 64; }
  25987. if (maxDepth === void 0) { maxDepth = 2; }
  25988. if (!this._selectionOctree) {
  25989. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25990. }
  25991. var worldExtends = this.getWorldExtends();
  25992. // Update octree
  25993. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25994. return this._selectionOctree;
  25995. };
  25996. // Picking
  25997. /**
  25998. * Creates a ray that can be used to pick in the scene
  25999. * @param x defines the x coordinate of the origin (on-screen)
  26000. * @param y defines the y coordinate of the origin (on-screen)
  26001. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  26002. * @param camera defines the camera to use for the picking
  26003. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  26004. * @returns a Ray
  26005. */
  26006. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  26007. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  26008. var result = BABYLON.Ray.Zero();
  26009. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  26010. return result;
  26011. };
  26012. /**
  26013. * Creates a ray that can be used to pick in the scene
  26014. * @param x defines the x coordinate of the origin (on-screen)
  26015. * @param y defines the y coordinate of the origin (on-screen)
  26016. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  26017. * @param result defines the ray where to store the picking ray
  26018. * @param camera defines the camera to use for the picking
  26019. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  26020. * @returns the current scene
  26021. */
  26022. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  26023. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  26024. var engine = this._engine;
  26025. if (!camera) {
  26026. if (!this.activeCamera)
  26027. throw new Error("Active camera not set");
  26028. camera = this.activeCamera;
  26029. }
  26030. var cameraViewport = camera.viewport;
  26031. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  26032. // Moving coordinates to local viewport world
  26033. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  26034. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  26035. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  26036. return this;
  26037. };
  26038. /**
  26039. * Creates a ray that can be used to pick in the scene
  26040. * @param x defines the x coordinate of the origin (on-screen)
  26041. * @param y defines the y coordinate of the origin (on-screen)
  26042. * @param camera defines the camera to use for the picking
  26043. * @returns a Ray
  26044. */
  26045. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  26046. var result = BABYLON.Ray.Zero();
  26047. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  26048. return result;
  26049. };
  26050. /**
  26051. * Creates a ray that can be used to pick in the scene
  26052. * @param x defines the x coordinate of the origin (on-screen)
  26053. * @param y defines the y coordinate of the origin (on-screen)
  26054. * @param result defines the ray where to store the picking ray
  26055. * @param camera defines the camera to use for the picking
  26056. * @returns the current scene
  26057. */
  26058. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  26059. if (!BABYLON.PickingInfo) {
  26060. return this;
  26061. }
  26062. var engine = this._engine;
  26063. if (!camera) {
  26064. if (!this.activeCamera)
  26065. throw new Error("Active camera not set");
  26066. camera = this.activeCamera;
  26067. }
  26068. var cameraViewport = camera.viewport;
  26069. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  26070. var identity = BABYLON.Matrix.Identity();
  26071. // Moving coordinates to local viewport world
  26072. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  26073. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  26074. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  26075. return this;
  26076. };
  26077. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  26078. if (!BABYLON.PickingInfo) {
  26079. return null;
  26080. }
  26081. var pickingInfo = null;
  26082. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  26083. var mesh = this.meshes[meshIndex];
  26084. if (predicate) {
  26085. if (!predicate(mesh)) {
  26086. continue;
  26087. }
  26088. }
  26089. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  26090. continue;
  26091. }
  26092. var world = mesh.getWorldMatrix();
  26093. var ray = rayFunction(world);
  26094. var result = mesh.intersects(ray, fastCheck);
  26095. if (!result || !result.hit)
  26096. continue;
  26097. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  26098. continue;
  26099. pickingInfo = result;
  26100. if (fastCheck) {
  26101. break;
  26102. }
  26103. }
  26104. return pickingInfo || new BABYLON.PickingInfo();
  26105. };
  26106. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  26107. if (!BABYLON.PickingInfo) {
  26108. return null;
  26109. }
  26110. var pickingInfos = new Array();
  26111. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  26112. var mesh = this.meshes[meshIndex];
  26113. if (predicate) {
  26114. if (!predicate(mesh)) {
  26115. continue;
  26116. }
  26117. }
  26118. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  26119. continue;
  26120. }
  26121. var world = mesh.getWorldMatrix();
  26122. var ray = rayFunction(world);
  26123. var result = mesh.intersects(ray, false);
  26124. if (!result || !result.hit)
  26125. continue;
  26126. pickingInfos.push(result);
  26127. }
  26128. return pickingInfos;
  26129. };
  26130. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  26131. if (!BABYLON.PickingInfo) {
  26132. return null;
  26133. }
  26134. var pickingInfo = null;
  26135. if (!camera) {
  26136. if (!this.activeCamera) {
  26137. return null;
  26138. }
  26139. camera = this.activeCamera;
  26140. }
  26141. if (this.spriteManagers.length > 0) {
  26142. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  26143. var spriteManager = this.spriteManagers[spriteIndex];
  26144. if (!spriteManager.isPickable) {
  26145. continue;
  26146. }
  26147. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  26148. if (!result || !result.hit)
  26149. continue;
  26150. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  26151. continue;
  26152. pickingInfo = result;
  26153. if (fastCheck) {
  26154. break;
  26155. }
  26156. }
  26157. }
  26158. return pickingInfo || new BABYLON.PickingInfo();
  26159. };
  26160. /** Launch a ray to try to pick a mesh in the scene
  26161. * @param x position on screen
  26162. * @param y position on screen
  26163. * @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
  26164. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  26165. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  26166. * @returns a PickingInfo
  26167. */
  26168. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  26169. var _this = this;
  26170. if (!BABYLON.PickingInfo) {
  26171. return null;
  26172. }
  26173. return this._internalPick(function (world) {
  26174. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  26175. return _this._tempPickingRay;
  26176. }, predicate, fastCheck);
  26177. };
  26178. /** Launch a ray to try to pick a sprite in the scene
  26179. * @param x position on screen
  26180. * @param y position on screen
  26181. * @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
  26182. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  26183. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  26184. * @returns a PickingInfo
  26185. */
  26186. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  26187. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  26188. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  26189. };
  26190. /** Use the given ray to pick a mesh in the scene
  26191. * @param ray The ray to use to pick meshes
  26192. * @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
  26193. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  26194. * @returns a PickingInfo
  26195. */
  26196. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  26197. var _this = this;
  26198. return this._internalPick(function (world) {
  26199. if (!_this._pickWithRayInverseMatrix) {
  26200. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  26201. }
  26202. world.invertToRef(_this._pickWithRayInverseMatrix);
  26203. if (!_this._cachedRayForTransform) {
  26204. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  26205. }
  26206. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  26207. return _this._cachedRayForTransform;
  26208. }, predicate, fastCheck);
  26209. };
  26210. /**
  26211. * Launch a ray to try to pick a mesh in the scene
  26212. * @param x X position on screen
  26213. * @param y Y position on screen
  26214. * @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
  26215. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  26216. * @returns an array of PickingInfo
  26217. */
  26218. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  26219. var _this = this;
  26220. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  26221. };
  26222. /**
  26223. * Launch a ray to try to pick a mesh in the scene
  26224. * @param ray Ray to use
  26225. * @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
  26226. * @returns an array of PickingInfo
  26227. */
  26228. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  26229. var _this = this;
  26230. return this._internalMultiPick(function (world) {
  26231. if (!_this._pickWithRayInverseMatrix) {
  26232. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  26233. }
  26234. world.invertToRef(_this._pickWithRayInverseMatrix);
  26235. if (!_this._cachedRayForTransform) {
  26236. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  26237. }
  26238. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  26239. return _this._cachedRayForTransform;
  26240. }, predicate);
  26241. };
  26242. /**
  26243. * Force the value of meshUnderPointer
  26244. * @param mesh defines the mesh to use
  26245. */
  26246. Scene.prototype.setPointerOverMesh = function (mesh) {
  26247. if (this._pointerOverMesh === mesh) {
  26248. return;
  26249. }
  26250. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  26251. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  26252. }
  26253. this._pointerOverMesh = mesh;
  26254. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  26255. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  26256. }
  26257. };
  26258. /**
  26259. * Gets the mesh under the pointer
  26260. * @returns a Mesh or null if no mesh is under the pointer
  26261. */
  26262. Scene.prototype.getPointerOverMesh = function () {
  26263. return this._pointerOverMesh;
  26264. };
  26265. /**
  26266. * Force the sprite under the pointer
  26267. * @param sprite defines the sprite to use
  26268. */
  26269. Scene.prototype.setPointerOverSprite = function (sprite) {
  26270. if (this._pointerOverSprite === sprite) {
  26271. return;
  26272. }
  26273. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  26274. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  26275. }
  26276. this._pointerOverSprite = sprite;
  26277. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  26278. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  26279. }
  26280. };
  26281. /**
  26282. * Gets the sprite under the pointer
  26283. * @returns a Sprite or null if no sprite is under the pointer
  26284. */
  26285. Scene.prototype.getPointerOverSprite = function () {
  26286. return this._pointerOverSprite;
  26287. };
  26288. // Physics
  26289. /**
  26290. * Gets the current physics engine
  26291. * @returns a PhysicsEngine or null if none attached
  26292. */
  26293. Scene.prototype.getPhysicsEngine = function () {
  26294. return this._physicsEngine;
  26295. };
  26296. /**
  26297. * Enables physics to the current scene
  26298. * @param gravity defines the scene's gravity for the physics engine
  26299. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  26300. * @return a boolean indicating if the physics engine was initialized
  26301. */
  26302. Scene.prototype.enablePhysics = function (gravity, plugin) {
  26303. if (gravity === void 0) { gravity = null; }
  26304. if (this._physicsEngine) {
  26305. return true;
  26306. }
  26307. try {
  26308. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  26309. return true;
  26310. }
  26311. catch (e) {
  26312. BABYLON.Tools.Error(e.message);
  26313. return false;
  26314. }
  26315. };
  26316. /**
  26317. * Disables and disposes the physics engine associated with the scene
  26318. */
  26319. Scene.prototype.disablePhysicsEngine = function () {
  26320. if (!this._physicsEngine) {
  26321. return;
  26322. }
  26323. this._physicsEngine.dispose();
  26324. this._physicsEngine = null;
  26325. };
  26326. /**
  26327. * Gets a boolean indicating if there is an active physics engine
  26328. * @returns a boolean indicating if there is an active physics engine
  26329. */
  26330. Scene.prototype.isPhysicsEnabled = function () {
  26331. return this._physicsEngine !== undefined;
  26332. };
  26333. /**
  26334. * Deletes a physics compound impostor
  26335. * @param compound defines the compound to delete
  26336. */
  26337. Scene.prototype.deleteCompoundImpostor = function (compound) {
  26338. var mesh = compound.parts[0].mesh;
  26339. if (mesh.physicsImpostor) {
  26340. mesh.physicsImpostor.dispose();
  26341. mesh.physicsImpostor = null;
  26342. }
  26343. };
  26344. // Misc.
  26345. /** @ignore */
  26346. Scene.prototype._rebuildGeometries = function () {
  26347. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  26348. var geometry = _a[_i];
  26349. geometry._rebuild();
  26350. }
  26351. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  26352. var mesh = _c[_b];
  26353. mesh._rebuild();
  26354. }
  26355. if (this.postProcessManager) {
  26356. this.postProcessManager._rebuild();
  26357. }
  26358. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  26359. var layer = _e[_d];
  26360. layer._rebuild();
  26361. }
  26362. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  26363. var effectLayer = _g[_f];
  26364. effectLayer._rebuild();
  26365. }
  26366. if (this._boundingBoxRenderer) {
  26367. this._boundingBoxRenderer._rebuild();
  26368. }
  26369. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  26370. var system = _j[_h];
  26371. system.rebuild();
  26372. }
  26373. if (this._postProcessRenderPipelineManager) {
  26374. this._postProcessRenderPipelineManager._rebuild();
  26375. }
  26376. };
  26377. /** @ignore */
  26378. Scene.prototype._rebuildTextures = function () {
  26379. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  26380. var texture = _a[_i];
  26381. texture._rebuild();
  26382. }
  26383. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26384. };
  26385. /**
  26386. * Creates a default light for the scene.
  26387. * @param replace Whether to replace the existing lights in the scene.
  26388. */
  26389. Scene.prototype.createDefaultLight = function (replace) {
  26390. if (replace === void 0) { replace = false; }
  26391. // Dispose existing light in replace mode.
  26392. if (replace) {
  26393. if (this.lights) {
  26394. for (var i = 0; i < this.lights.length; i++) {
  26395. this.lights[i].dispose();
  26396. }
  26397. }
  26398. }
  26399. // Light
  26400. if (this.lights.length === 0) {
  26401. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  26402. }
  26403. };
  26404. /**
  26405. * Creates a default camera for the scene.
  26406. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  26407. * @param replace Whether to replace the existing active camera in the scene.
  26408. * @param attachCameraControls Whether to attach camera controls to the canvas.
  26409. */
  26410. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  26411. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  26412. if (replace === void 0) { replace = false; }
  26413. if (attachCameraControls === void 0) { attachCameraControls = false; }
  26414. // Dispose existing camera in replace mode.
  26415. if (replace) {
  26416. if (this.activeCamera) {
  26417. this.activeCamera.dispose();
  26418. this.activeCamera = null;
  26419. }
  26420. }
  26421. // Camera
  26422. if (!this.activeCamera) {
  26423. var worldExtends = this.getWorldExtends();
  26424. var worldSize = worldExtends.max.subtract(worldExtends.min);
  26425. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  26426. var camera;
  26427. var radius = worldSize.length() * 1.5;
  26428. // empty scene scenario!
  26429. if (!isFinite(radius)) {
  26430. radius = 1;
  26431. worldCenter.copyFromFloats(0, 0, 0);
  26432. }
  26433. if (createArcRotateCamera) {
  26434. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  26435. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  26436. arcRotateCamera.wheelPrecision = 100 / radius;
  26437. camera = arcRotateCamera;
  26438. }
  26439. else {
  26440. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  26441. freeCamera.setTarget(worldCenter);
  26442. camera = freeCamera;
  26443. }
  26444. camera.minZ = radius * 0.01;
  26445. camera.maxZ = radius * 1000;
  26446. camera.speed = radius * 0.2;
  26447. this.activeCamera = camera;
  26448. var canvas = this.getEngine().getRenderingCanvas();
  26449. if (attachCameraControls && canvas) {
  26450. camera.attachControl(canvas);
  26451. }
  26452. }
  26453. };
  26454. /**
  26455. * Creates a default camera and a default light
  26456. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  26457. * @param replace defines if the camera and/or light will replace the existing ones
  26458. * @param attachCameraControls defines if attachControl will be called on the new camera
  26459. */
  26460. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  26461. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  26462. if (replace === void 0) { replace = false; }
  26463. if (attachCameraControls === void 0) { attachCameraControls = false; }
  26464. this.createDefaultLight(replace);
  26465. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  26466. };
  26467. /**
  26468. * Creates a new sky box
  26469. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  26470. * @param environmentTexture defines the texture to use as environment texture
  26471. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  26472. * @param scale defines the overall scale of the skybox
  26473. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  26474. * @returns a new mesh holding the sky box
  26475. */
  26476. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  26477. if (pbr === void 0) { pbr = false; }
  26478. if (scale === void 0) { scale = 1000; }
  26479. if (blur === void 0) { blur = 0; }
  26480. if (environmentTexture) {
  26481. this.environmentTexture = environmentTexture;
  26482. }
  26483. if (!this.environmentTexture) {
  26484. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  26485. return null;
  26486. }
  26487. // Skybox
  26488. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  26489. if (pbr) {
  26490. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  26491. hdrSkyboxMaterial.backFaceCulling = false;
  26492. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  26493. if (hdrSkyboxMaterial.reflectionTexture) {
  26494. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  26495. }
  26496. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  26497. hdrSkyboxMaterial.disableLighting = true;
  26498. hdrSkyboxMaterial.twoSidedLighting = true;
  26499. hdrSkybox.infiniteDistance = true;
  26500. hdrSkybox.material = hdrSkyboxMaterial;
  26501. }
  26502. else {
  26503. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  26504. skyboxMaterial.backFaceCulling = false;
  26505. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  26506. if (skyboxMaterial.reflectionTexture) {
  26507. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  26508. }
  26509. skyboxMaterial.disableLighting = true;
  26510. hdrSkybox.infiniteDistance = true;
  26511. hdrSkybox.material = skyboxMaterial;
  26512. }
  26513. return hdrSkybox;
  26514. };
  26515. /**
  26516. * Creates a new environment
  26517. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  26518. * @param options defines the options you can use to configure the environment
  26519. * @returns the new EnvironmentHelper
  26520. */
  26521. Scene.prototype.createDefaultEnvironment = function (options) {
  26522. if (BABYLON.EnvironmentHelper) {
  26523. return new BABYLON.EnvironmentHelper(options, this);
  26524. }
  26525. return null;
  26526. };
  26527. /**
  26528. * Creates a new VREXperienceHelper
  26529. * @see http://doc.babylonjs.com/how_to/webvr_helper
  26530. * @param webVROptions defines the options used to create the new VREXperienceHelper
  26531. * @returns a new VREXperienceHelper
  26532. */
  26533. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  26534. if (webVROptions === void 0) { webVROptions = {}; }
  26535. return new BABYLON.VRExperienceHelper(this, webVROptions);
  26536. };
  26537. // Tags
  26538. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  26539. if (tagsQuery === undefined) {
  26540. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  26541. return list;
  26542. }
  26543. var listByTags = [];
  26544. forEach = forEach || (function (item) { return; });
  26545. for (var i in list) {
  26546. var item = list[i];
  26547. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  26548. listByTags.push(item);
  26549. forEach(item);
  26550. }
  26551. }
  26552. return listByTags;
  26553. };
  26554. /**
  26555. * Get a list of meshes by tags
  26556. * @param tagsQuery defines the tags query to use
  26557. * @param forEach defines a predicate used to filter results
  26558. * @returns an array of Mesh
  26559. */
  26560. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  26561. return this._getByTags(this.meshes, tagsQuery, forEach);
  26562. };
  26563. /**
  26564. * Get a list of cameras by tags
  26565. * @param tagsQuery defines the tags query to use
  26566. * @param forEach defines a predicate used to filter results
  26567. * @returns an array of Camera
  26568. */
  26569. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  26570. return this._getByTags(this.cameras, tagsQuery, forEach);
  26571. };
  26572. /**
  26573. * Get a list of lights by tags
  26574. * @param tagsQuery defines the tags query to use
  26575. * @param forEach defines a predicate used to filter results
  26576. * @returns an array of Light
  26577. */
  26578. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  26579. return this._getByTags(this.lights, tagsQuery, forEach);
  26580. };
  26581. /**
  26582. * Get a list of materials by tags
  26583. * @param tagsQuery defines the tags query to use
  26584. * @param forEach defines a predicate used to filter results
  26585. * @returns an array of Material
  26586. */
  26587. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  26588. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  26589. };
  26590. /**
  26591. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  26592. * This allowed control for front to back rendering or reversly depending of the special needs.
  26593. *
  26594. * @param renderingGroupId The rendering group id corresponding to its index
  26595. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  26596. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  26597. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  26598. */
  26599. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  26600. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  26601. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  26602. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  26603. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  26604. };
  26605. /**
  26606. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  26607. *
  26608. * @param renderingGroupId The rendering group id corresponding to its index
  26609. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  26610. * @param depth Automatically clears depth between groups if true and autoClear is true.
  26611. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  26612. */
  26613. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  26614. if (depth === void 0) { depth = true; }
  26615. if (stencil === void 0) { stencil = true; }
  26616. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  26617. };
  26618. /**
  26619. * Will flag all materials as dirty to trigger new shader compilation
  26620. * @param flag defines the flag used to specify which material part must be marked as dirty
  26621. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  26622. */
  26623. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  26624. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  26625. var material = _a[_i];
  26626. if (predicate && !predicate(material)) {
  26627. continue;
  26628. }
  26629. material.markAsDirty(flag);
  26630. }
  26631. };
  26632. /** @ignore */
  26633. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  26634. var _this = this;
  26635. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  26636. this._activeRequests.push(request);
  26637. request.onCompleteObservable.add(function (request) {
  26638. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  26639. });
  26640. return request;
  26641. };
  26642. /** @ignore */
  26643. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  26644. var _this = this;
  26645. return new Promise(function (resolve, reject) {
  26646. _this._loadFile(url, function (data) {
  26647. resolve(data);
  26648. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  26649. reject(exception);
  26650. });
  26651. });
  26652. };
  26653. // Statics
  26654. Scene._FOGMODE_NONE = 0;
  26655. Scene._FOGMODE_EXP = 1;
  26656. Scene._FOGMODE_EXP2 = 2;
  26657. Scene._FOGMODE_LINEAR = 3;
  26658. Scene._uniqueIdCounter = 0;
  26659. /**
  26660. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  26661. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26662. */
  26663. Scene.MinDeltaTime = 1.0;
  26664. /**
  26665. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  26666. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26667. */
  26668. Scene.MaxDeltaTime = 1000.0;
  26669. /** The distance in pixel that you have to move to prevent some events */
  26670. Scene.DragMovementThreshold = 10; // in pixels
  26671. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  26672. Scene.LongPressDelay = 500; // in milliseconds
  26673. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  26674. Scene.DoubleClickDelay = 300; // in milliseconds
  26675. /** If you need to check double click without raising a single click at first click, enable this flag */
  26676. Scene.ExclusiveDoubleClickMode = false;
  26677. return Scene;
  26678. }());
  26679. BABYLON.Scene = Scene;
  26680. })(BABYLON || (BABYLON = {}));
  26681. //# sourceMappingURL=babylon.scene.js.map
  26682. "use strict";
  26683. var BABYLON;
  26684. (function (BABYLON) {
  26685. /**
  26686. * Set of assets to keep when moving a scene into an asset container.
  26687. */
  26688. var KeepAssets = /** @class */ (function () {
  26689. function KeepAssets() {
  26690. /**
  26691. * Cameras to keep.
  26692. */
  26693. this.cameras = new Array();
  26694. /**
  26695. * Lights to keep.
  26696. */
  26697. this.lights = new Array();
  26698. /**
  26699. * Meshes to keep.
  26700. */
  26701. this.meshes = new Array();
  26702. /**
  26703. * Skeletons to keep.
  26704. */
  26705. this.skeletons = new Array();
  26706. /**
  26707. * ParticleSystems to keep.
  26708. */
  26709. this.particleSystems = new Array();
  26710. /**
  26711. * Animations to keep.
  26712. */
  26713. this.animations = new Array();
  26714. /**
  26715. * AnimationGroups to keep.
  26716. */
  26717. this.animationGroups = new Array();
  26718. /**
  26719. * MultiMaterials to keep.
  26720. */
  26721. this.multiMaterials = new Array();
  26722. /**
  26723. * Materials to keep.
  26724. */
  26725. this.materials = new Array();
  26726. /**
  26727. * MorphTargetManagers to keep.
  26728. */
  26729. this.morphTargetManagers = new Array();
  26730. /**
  26731. * Geometries to keep.
  26732. */
  26733. this.geometries = new Array();
  26734. /**
  26735. * TransformNodes to keep.
  26736. */
  26737. this.transformNodes = new Array();
  26738. /**
  26739. * LensFlareSystems to keep.
  26740. */
  26741. this.lensFlareSystems = new Array();
  26742. /**
  26743. * ShadowGenerators to keep.
  26744. */
  26745. this.shadowGenerators = new Array();
  26746. /**
  26747. * ActionManagers to keep.
  26748. */
  26749. this.actionManagers = new Array();
  26750. /**
  26751. * Sounds to keep.
  26752. */
  26753. this.sounds = new Array();
  26754. /**
  26755. * Textures to keep.
  26756. */
  26757. this.textures = new Array();
  26758. }
  26759. return KeepAssets;
  26760. }());
  26761. BABYLON.KeepAssets = KeepAssets;
  26762. /**
  26763. * Container with a set of assets that can be added or removed from a scene.
  26764. */
  26765. var AssetContainer = /** @class */ (function () {
  26766. /**
  26767. * Instantiates an AssetContainer.
  26768. * @param scene The scene the AssetContainer belongs to.
  26769. */
  26770. function AssetContainer(scene) {
  26771. // Objects
  26772. /**
  26773. * Cameras populated in the container.
  26774. */
  26775. this.cameras = new Array();
  26776. /**
  26777. * Lights populated in the container.
  26778. */
  26779. this.lights = new Array();
  26780. /**
  26781. * Meshes populated in the container.
  26782. */
  26783. this.meshes = new Array();
  26784. /**
  26785. * Skeletons populated in the container.
  26786. */
  26787. this.skeletons = new Array();
  26788. /**
  26789. * ParticleSystems populated in the container.
  26790. */
  26791. this.particleSystems = new Array();
  26792. /**
  26793. * Animations populated in the container.
  26794. */
  26795. this.animations = new Array();
  26796. /**
  26797. * AnimationGroups populated in the container.
  26798. */
  26799. this.animationGroups = new Array();
  26800. /**
  26801. * MultiMaterials populated in the container.
  26802. */
  26803. this.multiMaterials = new Array();
  26804. /**
  26805. * Materials populated in the container.
  26806. */
  26807. this.materials = new Array();
  26808. /**
  26809. * MorphTargetManagers populated in the container.
  26810. */
  26811. this.morphTargetManagers = new Array();
  26812. /**
  26813. * Geometries populated in the container.
  26814. */
  26815. this.geometries = new Array();
  26816. /**
  26817. * TransformNodes populated in the container.
  26818. */
  26819. this.transformNodes = new Array();
  26820. /**
  26821. * LensFlareSystems populated in the container.
  26822. */
  26823. this.lensFlareSystems = new Array();
  26824. /**
  26825. * ShadowGenerators populated in the container.
  26826. */
  26827. this.shadowGenerators = new Array();
  26828. /**
  26829. * ActionManagers populated in the container.
  26830. */
  26831. this.actionManagers = new Array();
  26832. /**
  26833. * Sounds populated in the container.
  26834. */
  26835. this.sounds = new Array();
  26836. /**
  26837. * Textures populated in the container.
  26838. */
  26839. this.textures = new Array();
  26840. this.scene = scene;
  26841. }
  26842. /**
  26843. * Adds all the assets from the container to the scene.
  26844. */
  26845. AssetContainer.prototype.addAllToScene = function () {
  26846. var _this = this;
  26847. this.cameras.forEach(function (o) {
  26848. _this.scene.addCamera(o);
  26849. });
  26850. this.lights.forEach(function (o) {
  26851. _this.scene.addLight(o);
  26852. });
  26853. this.meshes.forEach(function (o) {
  26854. _this.scene.addMesh(o);
  26855. });
  26856. this.skeletons.forEach(function (o) {
  26857. _this.scene.addSkeleton(o);
  26858. });
  26859. this.particleSystems.forEach(function (o) {
  26860. _this.scene.addParticleSystem(o);
  26861. });
  26862. this.animations.forEach(function (o) {
  26863. _this.scene.addAnimation(o);
  26864. });
  26865. this.animationGroups.forEach(function (o) {
  26866. _this.scene.addAnimationGroup(o);
  26867. });
  26868. this.multiMaterials.forEach(function (o) {
  26869. _this.scene.addMultiMaterial(o);
  26870. });
  26871. this.materials.forEach(function (o) {
  26872. _this.scene.addMaterial(o);
  26873. });
  26874. this.morphTargetManagers.forEach(function (o) {
  26875. _this.scene.addMorphTargetManager(o);
  26876. });
  26877. this.geometries.forEach(function (o) {
  26878. _this.scene.addGeometry(o);
  26879. });
  26880. this.transformNodes.forEach(function (o) {
  26881. _this.scene.addTransformNode(o);
  26882. });
  26883. this.lensFlareSystems.forEach(function (o) {
  26884. _this.scene.addLensFlareSystem(o);
  26885. });
  26886. this.actionManagers.forEach(function (o) {
  26887. _this.scene.addActionManager(o);
  26888. });
  26889. this.sounds.forEach(function (o) {
  26890. o.play();
  26891. o.autoplay = true;
  26892. _this.scene.mainSoundTrack.AddSound(o);
  26893. });
  26894. this.textures.forEach(function (o) {
  26895. _this.scene.addTexture;
  26896. });
  26897. };
  26898. /**
  26899. * Removes all the assets in the container from the scene
  26900. */
  26901. AssetContainer.prototype.removeAllFromScene = function () {
  26902. var _this = this;
  26903. this.cameras.forEach(function (o) {
  26904. _this.scene.removeCamera(o);
  26905. });
  26906. this.lights.forEach(function (o) {
  26907. _this.scene.removeLight(o);
  26908. });
  26909. this.meshes.forEach(function (o) {
  26910. _this.scene.removeMesh(o);
  26911. });
  26912. this.skeletons.forEach(function (o) {
  26913. _this.scene.removeSkeleton(o);
  26914. });
  26915. this.particleSystems.forEach(function (o) {
  26916. _this.scene.removeParticleSystem(o);
  26917. });
  26918. this.animations.forEach(function (o) {
  26919. _this.scene.removeAnimation(o);
  26920. });
  26921. this.animationGroups.forEach(function (o) {
  26922. _this.scene.removeAnimationGroup(o);
  26923. });
  26924. this.multiMaterials.forEach(function (o) {
  26925. _this.scene.removeMultiMaterial(o);
  26926. });
  26927. this.materials.forEach(function (o) {
  26928. _this.scene.removeMaterial(o);
  26929. });
  26930. this.morphTargetManagers.forEach(function (o) {
  26931. _this.scene.removeMorphTargetManager(o);
  26932. });
  26933. this.geometries.forEach(function (o) {
  26934. _this.scene.removeGeometry(o);
  26935. });
  26936. this.transformNodes.forEach(function (o) {
  26937. _this.scene.removeTransformNode(o);
  26938. });
  26939. this.lensFlareSystems.forEach(function (o) {
  26940. _this.scene.removeLensFlareSystem(o);
  26941. });
  26942. this.actionManagers.forEach(function (o) {
  26943. _this.scene.removeActionManager(o);
  26944. });
  26945. this.sounds.forEach(function (o) {
  26946. o.stop();
  26947. o.autoplay = false;
  26948. _this.scene.mainSoundTrack.RemoveSound(o);
  26949. });
  26950. this.textures.forEach(function (o) {
  26951. _this.scene.removeTexture(o);
  26952. });
  26953. };
  26954. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26955. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26956. var asset = sourceAssets_1[_i];
  26957. var move = true;
  26958. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26959. var keepAsset = keepAssets_1[_a];
  26960. if (asset === keepAsset) {
  26961. move = false;
  26962. break;
  26963. }
  26964. }
  26965. if (move) {
  26966. targetAssets.push(asset);
  26967. }
  26968. }
  26969. };
  26970. /**
  26971. * Removes all the assets contained in the scene and adds them to the container.
  26972. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26973. */
  26974. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26975. if (keepAssets === undefined) {
  26976. keepAssets = new KeepAssets();
  26977. }
  26978. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26979. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26980. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26981. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26982. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26983. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26984. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  26985. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26986. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26987. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26988. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26989. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26990. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26991. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26992. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26993. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  26994. this.removeAllFromScene();
  26995. };
  26996. return AssetContainer;
  26997. }());
  26998. BABYLON.AssetContainer = AssetContainer;
  26999. })(BABYLON || (BABYLON = {}));
  27000. //# sourceMappingURL=babylon.assetContainer.js.map
  27001. "use strict";
  27002. var BABYLON;
  27003. (function (BABYLON) {
  27004. var Buffer = /** @class */ (function () {
  27005. /**
  27006. * Constructor
  27007. * @param engine the engine
  27008. * @param data the data to use for this buffer
  27009. * @param updatable whether the data is updatable
  27010. * @param stride the stride (optional)
  27011. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  27012. * @param instanced whether the buffer is instanced (optional)
  27013. * @param useBytes set to true if the stride in in bytes (optional)
  27014. */
  27015. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  27016. if (stride === void 0) { stride = 0; }
  27017. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  27018. if (instanced === void 0) { instanced = false; }
  27019. if (useBytes === void 0) { useBytes = false; }
  27020. if (engine instanceof BABYLON.Mesh) {
  27021. this._engine = engine.getScene().getEngine();
  27022. }
  27023. else {
  27024. this._engine = engine;
  27025. }
  27026. this._updatable = updatable;
  27027. this._instanced = instanced;
  27028. this._data = data;
  27029. this.byteStride = useBytes ? stride : stride * 4;
  27030. if (!postponeInternalCreation) {
  27031. this.create();
  27032. }
  27033. }
  27034. /**
  27035. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  27036. * @param kind defines the vertex buffer kind (position, normal, etc.)
  27037. * @param offset defines offset in the buffer (0 by default)
  27038. * @param size defines the size in floats of attributes (position is 3 for instance)
  27039. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  27040. * @param instanced defines if the vertex buffer contains indexed data
  27041. * @param useBytes defines if the offset and stride are in bytes
  27042. * @returns the new vertex buffer
  27043. */
  27044. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  27045. if (useBytes === void 0) { useBytes = false; }
  27046. var byteOffset = useBytes ? offset : offset * 4;
  27047. var byteStride = stride ? (useBytes ? stride : stride * 4) : this.byteStride;
  27048. // a lot of these parameters are ignored as they are overriden by the buffer
  27049. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  27050. };
  27051. // Properties
  27052. Buffer.prototype.isUpdatable = function () {
  27053. return this._updatable;
  27054. };
  27055. Buffer.prototype.getData = function () {
  27056. return this._data;
  27057. };
  27058. Buffer.prototype.getBuffer = function () {
  27059. return this._buffer;
  27060. };
  27061. /**
  27062. * Gets the stride in float32 units (i.e. byte stride / 4).
  27063. * May not be an integer if the byte stride is not divisible by 4.
  27064. * DEPRECATED. Use byteStride instead.
  27065. * @returns the stride in float32 units
  27066. */
  27067. Buffer.prototype.getStrideSize = function () {
  27068. return this.byteStride / 4;
  27069. };
  27070. // Methods
  27071. Buffer.prototype.create = function (data) {
  27072. if (data === void 0) { data = null; }
  27073. if (!data && this._buffer) {
  27074. return; // nothing to do
  27075. }
  27076. data = data || this._data;
  27077. if (!data) {
  27078. return;
  27079. }
  27080. if (!this._buffer) {
  27081. if (this._updatable) {
  27082. this._buffer = this._engine.createDynamicVertexBuffer(data);
  27083. this._data = data;
  27084. }
  27085. else {
  27086. this._buffer = this._engine.createVertexBuffer(data);
  27087. }
  27088. }
  27089. else if (this._updatable) {
  27090. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  27091. this._data = data;
  27092. }
  27093. };
  27094. Buffer.prototype._rebuild = function () {
  27095. this._buffer = null;
  27096. this.create(this._data);
  27097. };
  27098. Buffer.prototype.update = function (data) {
  27099. this.create(data);
  27100. };
  27101. /**
  27102. * Updates the data directly.
  27103. * @param data the new data
  27104. * @param offset the new offset
  27105. * @param vertexCount the vertex count (optional)
  27106. * @param useBytes set to true if the offset is in bytes
  27107. */
  27108. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  27109. if (useBytes === void 0) { useBytes = false; }
  27110. if (!this._buffer) {
  27111. return;
  27112. }
  27113. if (this._updatable) {
  27114. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * 4, (vertexCount ? vertexCount * this.byteStride : undefined));
  27115. this._data = null;
  27116. }
  27117. };
  27118. Buffer.prototype.dispose = function () {
  27119. if (!this._buffer) {
  27120. return;
  27121. }
  27122. if (this._engine._releaseBuffer(this._buffer)) {
  27123. this._buffer = null;
  27124. }
  27125. };
  27126. return Buffer;
  27127. }());
  27128. BABYLON.Buffer = Buffer;
  27129. })(BABYLON || (BABYLON = {}));
  27130. //# sourceMappingURL=babylon.buffer.js.map
  27131. "use strict";
  27132. var BABYLON;
  27133. (function (BABYLON) {
  27134. var VertexBuffer = /** @class */ (function () {
  27135. /**
  27136. * Constructor
  27137. * @param engine the engine
  27138. * @param data the data to use for this vertex buffer
  27139. * @param kind the vertex buffer kind
  27140. * @param updatable whether the data is updatable
  27141. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  27142. * @param stride the stride (optional)
  27143. * @param instanced whether the buffer is instanced (optional)
  27144. * @param offset the offset of the data (optional)
  27145. * @param size the number of components (optional)
  27146. * @param type the type of the component (optional)
  27147. * @param normalized whether the data contains normalized data (optional)
  27148. * @param useBytes set to true if stride and offset are in bytes (optional)
  27149. */
  27150. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  27151. if (normalized === void 0) { normalized = false; }
  27152. if (useBytes === void 0) { useBytes = false; }
  27153. if (data instanceof BABYLON.Buffer) {
  27154. this._buffer = data;
  27155. this._ownsBuffer = false;
  27156. }
  27157. else {
  27158. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  27159. this._ownsBuffer = true;
  27160. }
  27161. this._kind = kind;
  27162. if (type == undefined) {
  27163. var data_1 = this.getData();
  27164. this.type = VertexBuffer.FLOAT;
  27165. if (data_1 instanceof Int8Array)
  27166. this.type = VertexBuffer.BYTE;
  27167. else if (data_1 instanceof Uint8Array)
  27168. this.type = VertexBuffer.UNSIGNED_BYTE;
  27169. else if (data_1 instanceof Int16Array)
  27170. this.type = VertexBuffer.SHORT;
  27171. else if (data_1 instanceof Uint16Array)
  27172. this.type = VertexBuffer.UNSIGNED_SHORT;
  27173. else if (data_1 instanceof Int32Array)
  27174. this.type = VertexBuffer.INT;
  27175. else if (data_1 instanceof Uint32Array)
  27176. this.type = VertexBuffer.UNSIGNED_INT;
  27177. }
  27178. else {
  27179. this.type = type;
  27180. }
  27181. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  27182. if (useBytes) {
  27183. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  27184. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  27185. this.byteOffset = offset || 0;
  27186. }
  27187. else {
  27188. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  27189. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  27190. this.byteOffset = (offset || 0) * typeByteLength;
  27191. }
  27192. this.normalized = normalized;
  27193. this._instanced = instanced !== undefined ? instanced : false;
  27194. this._instanceDivisor = instanced ? 1 : 0;
  27195. }
  27196. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  27197. /**
  27198. * Gets or sets the instance divisor when in instanced mode
  27199. */
  27200. get: function () {
  27201. return this._instanceDivisor;
  27202. },
  27203. set: function (value) {
  27204. this._instanceDivisor = value;
  27205. if (value == 0) {
  27206. this._instanced = false;
  27207. }
  27208. else {
  27209. this._instanced = true;
  27210. }
  27211. },
  27212. enumerable: true,
  27213. configurable: true
  27214. });
  27215. VertexBuffer.prototype._rebuild = function () {
  27216. if (!this._buffer) {
  27217. return;
  27218. }
  27219. this._buffer._rebuild();
  27220. };
  27221. /**
  27222. * Returns the kind of the VertexBuffer (string).
  27223. */
  27224. VertexBuffer.prototype.getKind = function () {
  27225. return this._kind;
  27226. };
  27227. // Properties
  27228. /**
  27229. * Boolean : is the VertexBuffer updatable ?
  27230. */
  27231. VertexBuffer.prototype.isUpdatable = function () {
  27232. return this._buffer.isUpdatable();
  27233. };
  27234. /**
  27235. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  27236. */
  27237. VertexBuffer.prototype.getData = function () {
  27238. return this._buffer.getData();
  27239. };
  27240. /**
  27241. * Returns the WebGLBuffer associated to the VertexBuffer.
  27242. */
  27243. VertexBuffer.prototype.getBuffer = function () {
  27244. return this._buffer.getBuffer();
  27245. };
  27246. /**
  27247. * Returns the stride as a multiple of the type byte length.
  27248. * DEPRECATED. Use byteStride instead.
  27249. */
  27250. VertexBuffer.prototype.getStrideSize = function () {
  27251. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  27252. };
  27253. /**
  27254. * Returns the offset as a multiple of the type byte length.
  27255. * DEPRECATED. Use byteOffset instead.
  27256. */
  27257. VertexBuffer.prototype.getOffset = function () {
  27258. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  27259. };
  27260. /**
  27261. * Returns the number of components per vertex attribute (integer).
  27262. */
  27263. VertexBuffer.prototype.getSize = function () {
  27264. return this._size;
  27265. };
  27266. /**
  27267. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  27268. */
  27269. VertexBuffer.prototype.getIsInstanced = function () {
  27270. return this._instanced;
  27271. };
  27272. /**
  27273. * Returns the instancing divisor, zero for non-instanced (integer).
  27274. */
  27275. VertexBuffer.prototype.getInstanceDivisor = function () {
  27276. return this._instanceDivisor;
  27277. };
  27278. // Methods
  27279. /**
  27280. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  27281. * Returns the created WebGLBuffer.
  27282. */
  27283. VertexBuffer.prototype.create = function (data) {
  27284. return this._buffer.create(data);
  27285. };
  27286. /**
  27287. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  27288. * This function will create a new buffer if the current one is not updatable
  27289. * Returns the updated WebGLBuffer.
  27290. */
  27291. VertexBuffer.prototype.update = function (data) {
  27292. return this._buffer.update(data);
  27293. };
  27294. /**
  27295. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  27296. * Returns the directly updated WebGLBuffer.
  27297. */
  27298. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  27299. return this._buffer.updateDirectly(data, offset);
  27300. };
  27301. /**
  27302. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  27303. */
  27304. VertexBuffer.prototype.dispose = function () {
  27305. if (this._ownsBuffer) {
  27306. this._buffer.dispose();
  27307. }
  27308. };
  27309. /**
  27310. * Enumerates each value of this vertex buffer as numbers.
  27311. * @param count the number of values to enumerate
  27312. * @param callback the callback function called for each value
  27313. */
  27314. VertexBuffer.prototype.forEach = function (count, callback) {
  27315. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  27316. };
  27317. Object.defineProperty(VertexBuffer, "PositionKind", {
  27318. get: function () {
  27319. return VertexBuffer._PositionKind;
  27320. },
  27321. enumerable: true,
  27322. configurable: true
  27323. });
  27324. Object.defineProperty(VertexBuffer, "NormalKind", {
  27325. get: function () {
  27326. return VertexBuffer._NormalKind;
  27327. },
  27328. enumerable: true,
  27329. configurable: true
  27330. });
  27331. Object.defineProperty(VertexBuffer, "TangentKind", {
  27332. get: function () {
  27333. return VertexBuffer._TangentKind;
  27334. },
  27335. enumerable: true,
  27336. configurable: true
  27337. });
  27338. Object.defineProperty(VertexBuffer, "UVKind", {
  27339. get: function () {
  27340. return VertexBuffer._UVKind;
  27341. },
  27342. enumerable: true,
  27343. configurable: true
  27344. });
  27345. Object.defineProperty(VertexBuffer, "UV2Kind", {
  27346. get: function () {
  27347. return VertexBuffer._UV2Kind;
  27348. },
  27349. enumerable: true,
  27350. configurable: true
  27351. });
  27352. Object.defineProperty(VertexBuffer, "UV3Kind", {
  27353. get: function () {
  27354. return VertexBuffer._UV3Kind;
  27355. },
  27356. enumerable: true,
  27357. configurable: true
  27358. });
  27359. Object.defineProperty(VertexBuffer, "UV4Kind", {
  27360. get: function () {
  27361. return VertexBuffer._UV4Kind;
  27362. },
  27363. enumerable: true,
  27364. configurable: true
  27365. });
  27366. Object.defineProperty(VertexBuffer, "UV5Kind", {
  27367. get: function () {
  27368. return VertexBuffer._UV5Kind;
  27369. },
  27370. enumerable: true,
  27371. configurable: true
  27372. });
  27373. Object.defineProperty(VertexBuffer, "UV6Kind", {
  27374. get: function () {
  27375. return VertexBuffer._UV6Kind;
  27376. },
  27377. enumerable: true,
  27378. configurable: true
  27379. });
  27380. Object.defineProperty(VertexBuffer, "ColorKind", {
  27381. get: function () {
  27382. return VertexBuffer._ColorKind;
  27383. },
  27384. enumerable: true,
  27385. configurable: true
  27386. });
  27387. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  27388. get: function () {
  27389. return VertexBuffer._MatricesIndicesKind;
  27390. },
  27391. enumerable: true,
  27392. configurable: true
  27393. });
  27394. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  27395. get: function () {
  27396. return VertexBuffer._MatricesWeightsKind;
  27397. },
  27398. enumerable: true,
  27399. configurable: true
  27400. });
  27401. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  27402. get: function () {
  27403. return VertexBuffer._MatricesIndicesExtraKind;
  27404. },
  27405. enumerable: true,
  27406. configurable: true
  27407. });
  27408. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  27409. get: function () {
  27410. return VertexBuffer._MatricesWeightsExtraKind;
  27411. },
  27412. enumerable: true,
  27413. configurable: true
  27414. });
  27415. /**
  27416. * Deduces the stride given a kind.
  27417. * @param kind The kind string to deduce
  27418. * @returns The deduced stride
  27419. */
  27420. VertexBuffer.DeduceStride = function (kind) {
  27421. switch (kind) {
  27422. case VertexBuffer.UVKind:
  27423. case VertexBuffer.UV2Kind:
  27424. case VertexBuffer.UV3Kind:
  27425. case VertexBuffer.UV4Kind:
  27426. case VertexBuffer.UV5Kind:
  27427. case VertexBuffer.UV6Kind:
  27428. return 2;
  27429. case VertexBuffer.NormalKind:
  27430. case VertexBuffer.PositionKind:
  27431. return 3;
  27432. case VertexBuffer.ColorKind:
  27433. case VertexBuffer.MatricesIndicesKind:
  27434. case VertexBuffer.MatricesIndicesExtraKind:
  27435. case VertexBuffer.MatricesWeightsKind:
  27436. case VertexBuffer.MatricesWeightsExtraKind:
  27437. case VertexBuffer.TangentKind:
  27438. return 4;
  27439. default:
  27440. throw new Error("Invalid kind '" + kind + "'");
  27441. }
  27442. };
  27443. /**
  27444. * Gets the byte length of the given type.
  27445. * @param type the type
  27446. * @returns the number of bytes
  27447. */
  27448. VertexBuffer.GetTypeByteLength = function (type) {
  27449. switch (type) {
  27450. case VertexBuffer.BYTE:
  27451. case VertexBuffer.UNSIGNED_BYTE:
  27452. return 1;
  27453. case VertexBuffer.SHORT:
  27454. case VertexBuffer.UNSIGNED_SHORT:
  27455. return 2;
  27456. case VertexBuffer.INT:
  27457. case VertexBuffer.FLOAT:
  27458. return 4;
  27459. default:
  27460. throw new Error("Invalid type '" + type + "'");
  27461. }
  27462. };
  27463. /**
  27464. * Enumerates each value of the given parameters as numbers.
  27465. * @param data the data to enumerate
  27466. * @param byteOffset the byte offset of the data
  27467. * @param byteStride the byte stride of the data
  27468. * @param componentCount the number of components per element
  27469. * @param componentType the type of the component
  27470. * @param count the total number of components
  27471. * @param normalized whether the data is normalized
  27472. * @param callback the callback function called for each value
  27473. */
  27474. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  27475. if (data instanceof Array) {
  27476. var offset = byteOffset / 4;
  27477. var stride = byteStride / 4;
  27478. for (var index = 0; index < count; index += componentCount) {
  27479. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  27480. callback(data[offset + componentIndex], index + componentIndex);
  27481. }
  27482. offset += stride;
  27483. }
  27484. }
  27485. else {
  27486. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  27487. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  27488. for (var index = 0; index < count; index += componentCount) {
  27489. var componentByteOffset = byteOffset;
  27490. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  27491. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  27492. callback(value, index + componentIndex);
  27493. componentByteOffset += componentByteLength;
  27494. }
  27495. byteOffset += byteStride;
  27496. }
  27497. }
  27498. };
  27499. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  27500. switch (type) {
  27501. case VertexBuffer.BYTE: {
  27502. var value = dataView.getInt8(byteOffset);
  27503. if (normalized) {
  27504. value = (value + 0.5) / 127.5;
  27505. }
  27506. return value;
  27507. }
  27508. case VertexBuffer.UNSIGNED_BYTE: {
  27509. var value = dataView.getUint8(byteOffset);
  27510. if (normalized) {
  27511. value = value / 255;
  27512. }
  27513. return value;
  27514. }
  27515. case VertexBuffer.SHORT: {
  27516. var value = dataView.getInt16(byteOffset, true);
  27517. if (normalized) {
  27518. value = (value + 0.5) / 16383.5;
  27519. }
  27520. return value;
  27521. }
  27522. case VertexBuffer.UNSIGNED_SHORT: {
  27523. var value = dataView.getUint16(byteOffset, true);
  27524. if (normalized) {
  27525. value = value / 65535;
  27526. }
  27527. return value;
  27528. }
  27529. case VertexBuffer.FLOAT: {
  27530. return dataView.getFloat32(byteOffset, true);
  27531. }
  27532. default: {
  27533. throw new Error("Invalid component type " + type);
  27534. }
  27535. }
  27536. };
  27537. /**
  27538. * The byte type.
  27539. */
  27540. VertexBuffer.BYTE = 5120;
  27541. /**
  27542. * The unsigned byte type.
  27543. */
  27544. VertexBuffer.UNSIGNED_BYTE = 5121;
  27545. /**
  27546. * The short type.
  27547. */
  27548. VertexBuffer.SHORT = 5122;
  27549. /**
  27550. * The unsigned short type.
  27551. */
  27552. VertexBuffer.UNSIGNED_SHORT = 5123;
  27553. /**
  27554. * The integer type.
  27555. */
  27556. VertexBuffer.INT = 5124;
  27557. /**
  27558. * The unsigned integer type.
  27559. */
  27560. VertexBuffer.UNSIGNED_INT = 5125;
  27561. /**
  27562. * The float type.
  27563. */
  27564. VertexBuffer.FLOAT = 5126;
  27565. // Enums
  27566. VertexBuffer._PositionKind = "position";
  27567. VertexBuffer._NormalKind = "normal";
  27568. VertexBuffer._TangentKind = "tangent";
  27569. VertexBuffer._UVKind = "uv";
  27570. VertexBuffer._UV2Kind = "uv2";
  27571. VertexBuffer._UV3Kind = "uv3";
  27572. VertexBuffer._UV4Kind = "uv4";
  27573. VertexBuffer._UV5Kind = "uv5";
  27574. VertexBuffer._UV6Kind = "uv6";
  27575. VertexBuffer._ColorKind = "color";
  27576. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  27577. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  27578. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  27579. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  27580. return VertexBuffer;
  27581. }());
  27582. BABYLON.VertexBuffer = VertexBuffer;
  27583. })(BABYLON || (BABYLON = {}));
  27584. //# sourceMappingURL=babylon.vertexBuffer.js.map
  27585. "use strict";
  27586. var BABYLON;
  27587. (function (BABYLON) {
  27588. /**
  27589. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  27590. */
  27591. var DummyInternalTextureTracker = /** @class */ (function () {
  27592. function DummyInternalTextureTracker() {
  27593. /**
  27594. * Gets or set the previous tracker in the list
  27595. */
  27596. this.previous = null;
  27597. /**
  27598. * Gets or set the next tracker in the list
  27599. */
  27600. this.next = null;
  27601. }
  27602. return DummyInternalTextureTracker;
  27603. }());
  27604. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  27605. })(BABYLON || (BABYLON = {}));
  27606. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  27607. "use strict";
  27608. var BABYLON;
  27609. (function (BABYLON) {
  27610. /**
  27611. * Class used to store data associated with WebGL texture data for the engine
  27612. * This class should not be used directly
  27613. */
  27614. var InternalTexture = /** @class */ (function () {
  27615. /**
  27616. * Creates a new InternalTexture
  27617. * @param engine defines the engine to use
  27618. * @param dataSource defines the type of data that will be used
  27619. */
  27620. function InternalTexture(engine, dataSource) {
  27621. /**
  27622. * Observable called when the texture is loaded
  27623. */
  27624. this.onLoadedObservable = new BABYLON.Observable();
  27625. /**
  27626. * Gets or set the previous tracker in the list
  27627. */
  27628. this.previous = null;
  27629. /**
  27630. * Gets or set the next tracker in the list
  27631. */
  27632. this.next = null;
  27633. // Private
  27634. /** @ignore */
  27635. this._initialSlot = -1;
  27636. /** @ignore */
  27637. this._designatedSlot = -1;
  27638. /** @ignore */
  27639. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  27640. /** @ignore */
  27641. this._comparisonFunction = 0;
  27642. /** @ignore */
  27643. this._references = 1;
  27644. this._engine = engine;
  27645. this._dataSource = dataSource;
  27646. this._webGLTexture = engine._createTexture();
  27647. }
  27648. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  27649. /**
  27650. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  27651. */
  27652. get: function () {
  27653. return this._dataSource;
  27654. },
  27655. enumerable: true,
  27656. configurable: true
  27657. });
  27658. /**
  27659. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  27660. */
  27661. InternalTexture.prototype.incrementReferences = function () {
  27662. this._references++;
  27663. };
  27664. /**
  27665. * Change the size of the texture (not the size of the content)
  27666. * @param width defines the new width
  27667. * @param height defines the new height
  27668. * @param depth defines the new depth (1 by default)
  27669. */
  27670. InternalTexture.prototype.updateSize = function (width, height, depth) {
  27671. if (depth === void 0) { depth = 1; }
  27672. this.width = width;
  27673. this.height = height;
  27674. this.depth = depth;
  27675. this.baseWidth = width;
  27676. this.baseHeight = height;
  27677. this.baseDepth = depth;
  27678. this._size = width * height * depth;
  27679. };
  27680. /** @ignore */
  27681. InternalTexture.prototype._rebuild = function () {
  27682. var _this = this;
  27683. var proxy;
  27684. this.isReady = false;
  27685. this._cachedCoordinatesMode = null;
  27686. this._cachedWrapU = null;
  27687. this._cachedWrapV = null;
  27688. this._cachedAnisotropicFilteringLevel = null;
  27689. switch (this._dataSource) {
  27690. case InternalTexture.DATASOURCE_TEMP:
  27691. return;
  27692. case InternalTexture.DATASOURCE_URL:
  27693. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  27694. _this.isReady = true;
  27695. }, null, this._buffer, undefined, this.format);
  27696. proxy._swapAndDie(this);
  27697. return;
  27698. case InternalTexture.DATASOURCE_RAW:
  27699. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  27700. proxy._swapAndDie(this);
  27701. this.isReady = true;
  27702. return;
  27703. case InternalTexture.DATASOURCE_RAW3D:
  27704. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  27705. proxy._swapAndDie(this);
  27706. this.isReady = true;
  27707. return;
  27708. case InternalTexture.DATASOURCE_DYNAMIC:
  27709. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  27710. proxy._swapAndDie(this);
  27711. // The engine will make sure to update content so no need to flag it as isReady = true
  27712. return;
  27713. case InternalTexture.DATASOURCE_RENDERTARGET:
  27714. var options = new BABYLON.RenderTargetCreationOptions();
  27715. options.generateDepthBuffer = this._generateDepthBuffer;
  27716. options.generateMipMaps = this.generateMipMaps;
  27717. options.generateStencilBuffer = this._generateStencilBuffer;
  27718. options.samplingMode = this.samplingMode;
  27719. options.type = this.type;
  27720. if (this.isCube) {
  27721. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  27722. }
  27723. else {
  27724. var size = {
  27725. width: this.width,
  27726. height: this.height
  27727. };
  27728. proxy = this._engine.createRenderTargetTexture(size, options);
  27729. }
  27730. proxy._swapAndDie(this);
  27731. this.isReady = true;
  27732. return;
  27733. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  27734. var depthTextureOptions = {
  27735. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  27736. comparisonFunction: this._comparisonFunction,
  27737. generateStencil: this._generateStencilBuffer,
  27738. isCube: this.isCube
  27739. };
  27740. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  27741. proxy._swapAndDie(this);
  27742. this.isReady = true;
  27743. return;
  27744. case InternalTexture.DATASOURCE_CUBE:
  27745. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  27746. _this.isReady = true;
  27747. }, null, this.format, this._extension);
  27748. proxy._swapAndDie(this);
  27749. return;
  27750. case InternalTexture.DATASOURCE_CUBERAW:
  27751. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  27752. proxy._swapAndDie(this);
  27753. this.isReady = true;
  27754. return;
  27755. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  27756. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  27757. if (proxy) {
  27758. proxy._swapAndDie(_this);
  27759. }
  27760. _this.isReady = true;
  27761. }, null, this.format, this._extension);
  27762. return;
  27763. }
  27764. };
  27765. InternalTexture.prototype._swapAndDie = function (target) {
  27766. target._webGLTexture = this._webGLTexture;
  27767. if (this._framebuffer) {
  27768. target._framebuffer = this._framebuffer;
  27769. }
  27770. if (this._depthStencilBuffer) {
  27771. target._depthStencilBuffer = this._depthStencilBuffer;
  27772. }
  27773. if (this._lodTextureHigh) {
  27774. if (target._lodTextureHigh) {
  27775. target._lodTextureHigh.dispose();
  27776. }
  27777. target._lodTextureHigh = this._lodTextureHigh;
  27778. }
  27779. if (this._lodTextureMid) {
  27780. if (target._lodTextureMid) {
  27781. target._lodTextureMid.dispose();
  27782. }
  27783. target._lodTextureMid = this._lodTextureMid;
  27784. }
  27785. if (this._lodTextureLow) {
  27786. if (target._lodTextureLow) {
  27787. target._lodTextureLow.dispose();
  27788. }
  27789. target._lodTextureLow = this._lodTextureLow;
  27790. }
  27791. var cache = this._engine.getLoadedTexturesCache();
  27792. var index = cache.indexOf(this);
  27793. if (index !== -1) {
  27794. cache.splice(index, 1);
  27795. }
  27796. };
  27797. /**
  27798. * Dispose the current allocated resources
  27799. */
  27800. InternalTexture.prototype.dispose = function () {
  27801. if (!this._webGLTexture) {
  27802. return;
  27803. }
  27804. this._references--;
  27805. if (this._references === 0) {
  27806. this._engine._releaseTexture(this);
  27807. this._webGLTexture = null;
  27808. this.previous = null;
  27809. this.next = null;
  27810. }
  27811. };
  27812. /**
  27813. * The source of the texture data is unknown
  27814. */
  27815. InternalTexture.DATASOURCE_UNKNOWN = 0;
  27816. /**
  27817. * Texture data comes from an URL
  27818. */
  27819. InternalTexture.DATASOURCE_URL = 1;
  27820. /**
  27821. * Texture data is only used for temporary storage
  27822. */
  27823. InternalTexture.DATASOURCE_TEMP = 2;
  27824. /**
  27825. * Texture data comes from raw data (ArrayBuffer)
  27826. */
  27827. InternalTexture.DATASOURCE_RAW = 3;
  27828. /**
  27829. * Texture content is dynamic (video or dynamic texture)
  27830. */
  27831. InternalTexture.DATASOURCE_DYNAMIC = 4;
  27832. /**
  27833. * Texture content is generated by rendering to it
  27834. */
  27835. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  27836. /**
  27837. * Texture content is part of a multi render target process
  27838. */
  27839. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  27840. /**
  27841. * Texture data comes from a cube data file
  27842. */
  27843. InternalTexture.DATASOURCE_CUBE = 7;
  27844. /**
  27845. * Texture data comes from a raw cube data
  27846. */
  27847. InternalTexture.DATASOURCE_CUBERAW = 8;
  27848. /**
  27849. * Texture data come from a prefiltered cube data file
  27850. */
  27851. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  27852. /**
  27853. * Texture content is raw 3D data
  27854. */
  27855. InternalTexture.DATASOURCE_RAW3D = 10;
  27856. /**
  27857. * Texture content is a depth texture
  27858. */
  27859. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  27860. return InternalTexture;
  27861. }());
  27862. BABYLON.InternalTexture = InternalTexture;
  27863. })(BABYLON || (BABYLON = {}));
  27864. //# sourceMappingURL=babylon.internalTexture.js.map
  27865. "use strict";
  27866. var BABYLON;
  27867. (function (BABYLON) {
  27868. var BaseTexture = /** @class */ (function () {
  27869. function BaseTexture(scene) {
  27870. this._hasAlpha = false;
  27871. this.getAlphaFromRGB = false;
  27872. this.level = 1;
  27873. this.coordinatesIndex = 0;
  27874. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  27875. /**
  27876. * | Value | Type | Description |
  27877. * | ----- | ------------------ | ----------- |
  27878. * | 0 | CLAMP_ADDRESSMODE | |
  27879. * | 1 | WRAP_ADDRESSMODE | |
  27880. * | 2 | MIRROR_ADDRESSMODE | |
  27881. */
  27882. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27883. /**
  27884. * | Value | Type | Description |
  27885. * | ----- | ------------------ | ----------- |
  27886. * | 0 | CLAMP_ADDRESSMODE | |
  27887. * | 1 | WRAP_ADDRESSMODE | |
  27888. * | 2 | MIRROR_ADDRESSMODE | |
  27889. */
  27890. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27891. /**
  27892. * | Value | Type | Description |
  27893. * | ----- | ------------------ | ----------- |
  27894. * | 0 | CLAMP_ADDRESSMODE | |
  27895. * | 1 | WRAP_ADDRESSMODE | |
  27896. * | 2 | MIRROR_ADDRESSMODE | |
  27897. */
  27898. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  27899. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  27900. this.isCube = false;
  27901. this.is3D = false;
  27902. this.gammaSpace = true;
  27903. this.invertZ = false;
  27904. this.lodLevelInAlpha = false;
  27905. this.lodGenerationOffset = 0.0;
  27906. this.lodGenerationScale = 0.8;
  27907. this.isRenderTarget = false;
  27908. this.animations = new Array();
  27909. /**
  27910. * An event triggered when the texture is disposed.
  27911. */
  27912. this.onDisposeObservable = new BABYLON.Observable();
  27913. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27914. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27915. if (this._scene) {
  27916. this._scene.textures.push(this);
  27917. }
  27918. this._uid = null;
  27919. }
  27920. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  27921. get: function () {
  27922. return this._hasAlpha;
  27923. },
  27924. set: function (value) {
  27925. if (this._hasAlpha === value) {
  27926. return;
  27927. }
  27928. this._hasAlpha = value;
  27929. if (this._scene) {
  27930. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  27931. }
  27932. },
  27933. enumerable: true,
  27934. configurable: true
  27935. });
  27936. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  27937. get: function () {
  27938. return this._coordinatesMode;
  27939. },
  27940. /**
  27941. * How a texture is mapped.
  27942. *
  27943. * | Value | Type | Description |
  27944. * | ----- | ----------------------------------- | ----------- |
  27945. * | 0 | EXPLICIT_MODE | |
  27946. * | 1 | SPHERICAL_MODE | |
  27947. * | 2 | PLANAR_MODE | |
  27948. * | 3 | CUBIC_MODE | |
  27949. * | 4 | PROJECTION_MODE | |
  27950. * | 5 | SKYBOX_MODE | |
  27951. * | 6 | INVCUBIC_MODE | |
  27952. * | 7 | EQUIRECTANGULAR_MODE | |
  27953. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  27954. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  27955. */
  27956. set: function (value) {
  27957. if (this._coordinatesMode === value) {
  27958. return;
  27959. }
  27960. this._coordinatesMode = value;
  27961. if (this._scene) {
  27962. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27963. }
  27964. },
  27965. enumerable: true,
  27966. configurable: true
  27967. });
  27968. Object.defineProperty(BaseTexture.prototype, "uid", {
  27969. get: function () {
  27970. if (!this._uid) {
  27971. this._uid = BABYLON.Tools.RandomId();
  27972. }
  27973. return this._uid;
  27974. },
  27975. enumerable: true,
  27976. configurable: true
  27977. });
  27978. BaseTexture.prototype.toString = function () {
  27979. return this.name;
  27980. };
  27981. BaseTexture.prototype.getClassName = function () {
  27982. return "BaseTexture";
  27983. };
  27984. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27985. set: function (callback) {
  27986. if (this._onDisposeObserver) {
  27987. this.onDisposeObservable.remove(this._onDisposeObserver);
  27988. }
  27989. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27990. },
  27991. enumerable: true,
  27992. configurable: true
  27993. });
  27994. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27995. get: function () {
  27996. return true;
  27997. },
  27998. enumerable: true,
  27999. configurable: true
  28000. });
  28001. BaseTexture.prototype.getScene = function () {
  28002. return this._scene;
  28003. };
  28004. BaseTexture.prototype.getTextureMatrix = function () {
  28005. return BABYLON.Matrix.IdentityReadOnly;
  28006. };
  28007. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  28008. return BABYLON.Matrix.IdentityReadOnly;
  28009. };
  28010. BaseTexture.prototype.getInternalTexture = function () {
  28011. return this._texture;
  28012. };
  28013. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  28014. return !this.isBlocking || this.isReady();
  28015. };
  28016. BaseTexture.prototype.isReady = function () {
  28017. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28018. this.delayLoad();
  28019. return false;
  28020. }
  28021. if (this._texture) {
  28022. return this._texture.isReady;
  28023. }
  28024. return false;
  28025. };
  28026. BaseTexture.prototype.getSize = function () {
  28027. if (this._texture && this._texture.width) {
  28028. return new BABYLON.Size(this._texture.width, this._texture.height);
  28029. }
  28030. if (this._texture && this._texture._size) {
  28031. return new BABYLON.Size(this._texture._size, this._texture._size);
  28032. }
  28033. return BABYLON.Size.Zero();
  28034. };
  28035. BaseTexture.prototype.getBaseSize = function () {
  28036. if (!this.isReady() || !this._texture)
  28037. return BABYLON.Size.Zero();
  28038. if (this._texture._size) {
  28039. return new BABYLON.Size(this._texture._size, this._texture._size);
  28040. }
  28041. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  28042. };
  28043. BaseTexture.prototype.scale = function (ratio) {
  28044. };
  28045. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  28046. get: function () {
  28047. return false;
  28048. },
  28049. enumerable: true,
  28050. configurable: true
  28051. });
  28052. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  28053. if (!this._scene) {
  28054. return null;
  28055. }
  28056. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  28057. for (var index = 0; index < texturesCache.length; index++) {
  28058. var texturesCacheEntry = texturesCache[index];
  28059. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  28060. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  28061. texturesCacheEntry.incrementReferences();
  28062. return texturesCacheEntry;
  28063. }
  28064. }
  28065. }
  28066. return null;
  28067. };
  28068. BaseTexture.prototype._rebuild = function () {
  28069. };
  28070. BaseTexture.prototype.delayLoad = function () {
  28071. };
  28072. BaseTexture.prototype.clone = function () {
  28073. return null;
  28074. };
  28075. Object.defineProperty(BaseTexture.prototype, "textureType", {
  28076. get: function () {
  28077. if (!this._texture) {
  28078. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  28079. }
  28080. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  28081. },
  28082. enumerable: true,
  28083. configurable: true
  28084. });
  28085. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  28086. get: function () {
  28087. if (!this._texture) {
  28088. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  28089. }
  28090. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  28091. },
  28092. enumerable: true,
  28093. configurable: true
  28094. });
  28095. BaseTexture.prototype.readPixels = function (faceIndex) {
  28096. if (faceIndex === void 0) { faceIndex = 0; }
  28097. if (!this._texture) {
  28098. return null;
  28099. }
  28100. var size = this.getSize();
  28101. var scene = this.getScene();
  28102. if (!scene) {
  28103. return null;
  28104. }
  28105. var engine = scene.getEngine();
  28106. if (this._texture.isCube) {
  28107. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  28108. }
  28109. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  28110. };
  28111. BaseTexture.prototype.releaseInternalTexture = function () {
  28112. if (this._texture) {
  28113. this._texture.dispose();
  28114. this._texture = null;
  28115. }
  28116. };
  28117. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  28118. get: function () {
  28119. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  28120. return null;
  28121. }
  28122. if (!this._texture._sphericalPolynomial) {
  28123. this._texture._sphericalPolynomial =
  28124. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  28125. }
  28126. return this._texture._sphericalPolynomial;
  28127. },
  28128. set: function (value) {
  28129. if (this._texture) {
  28130. this._texture._sphericalPolynomial = value;
  28131. }
  28132. },
  28133. enumerable: true,
  28134. configurable: true
  28135. });
  28136. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  28137. get: function () {
  28138. if (this._texture) {
  28139. return this._texture._lodTextureHigh;
  28140. }
  28141. return null;
  28142. },
  28143. enumerable: true,
  28144. configurable: true
  28145. });
  28146. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  28147. get: function () {
  28148. if (this._texture) {
  28149. return this._texture._lodTextureMid;
  28150. }
  28151. return null;
  28152. },
  28153. enumerable: true,
  28154. configurable: true
  28155. });
  28156. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  28157. get: function () {
  28158. if (this._texture) {
  28159. return this._texture._lodTextureLow;
  28160. }
  28161. return null;
  28162. },
  28163. enumerable: true,
  28164. configurable: true
  28165. });
  28166. BaseTexture.prototype.dispose = function () {
  28167. if (!this._scene) {
  28168. return;
  28169. }
  28170. // Animations
  28171. this._scene.stopAnimation(this);
  28172. // Remove from scene
  28173. this._scene._removePendingData(this);
  28174. var index = this._scene.textures.indexOf(this);
  28175. if (index >= 0) {
  28176. this._scene.textures.splice(index, 1);
  28177. }
  28178. if (this._texture === undefined) {
  28179. return;
  28180. }
  28181. // Release
  28182. this.releaseInternalTexture();
  28183. // Callback
  28184. this.onDisposeObservable.notifyObservers(this);
  28185. this.onDisposeObservable.clear();
  28186. };
  28187. BaseTexture.prototype.serialize = function () {
  28188. if (!this.name) {
  28189. return null;
  28190. }
  28191. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  28192. // Animations
  28193. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28194. return serializationObject;
  28195. };
  28196. BaseTexture.WhenAllReady = function (textures, callback) {
  28197. var numRemaining = textures.length;
  28198. if (numRemaining === 0) {
  28199. callback();
  28200. return;
  28201. }
  28202. var _loop_1 = function () {
  28203. texture = textures[i];
  28204. if (texture.isReady()) {
  28205. if (--numRemaining === 0) {
  28206. callback();
  28207. }
  28208. }
  28209. else {
  28210. onLoadObservable = texture.onLoadObservable;
  28211. var onLoadCallback_1 = function () {
  28212. onLoadObservable.removeCallback(onLoadCallback_1);
  28213. if (--numRemaining === 0) {
  28214. callback();
  28215. }
  28216. };
  28217. onLoadObservable.add(onLoadCallback_1);
  28218. }
  28219. };
  28220. var texture, onLoadObservable;
  28221. for (var i = 0; i < textures.length; i++) {
  28222. _loop_1();
  28223. }
  28224. };
  28225. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  28226. __decorate([
  28227. BABYLON.serialize()
  28228. ], BaseTexture.prototype, "name", void 0);
  28229. __decorate([
  28230. BABYLON.serialize("hasAlpha")
  28231. ], BaseTexture.prototype, "_hasAlpha", void 0);
  28232. __decorate([
  28233. BABYLON.serialize()
  28234. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  28235. __decorate([
  28236. BABYLON.serialize()
  28237. ], BaseTexture.prototype, "level", void 0);
  28238. __decorate([
  28239. BABYLON.serialize()
  28240. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  28241. __decorate([
  28242. BABYLON.serialize("coordinatesMode")
  28243. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  28244. __decorate([
  28245. BABYLON.serialize()
  28246. ], BaseTexture.prototype, "wrapU", void 0);
  28247. __decorate([
  28248. BABYLON.serialize()
  28249. ], BaseTexture.prototype, "wrapV", void 0);
  28250. __decorate([
  28251. BABYLON.serialize()
  28252. ], BaseTexture.prototype, "wrapR", void 0);
  28253. __decorate([
  28254. BABYLON.serialize()
  28255. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  28256. __decorate([
  28257. BABYLON.serialize()
  28258. ], BaseTexture.prototype, "isCube", void 0);
  28259. __decorate([
  28260. BABYLON.serialize()
  28261. ], BaseTexture.prototype, "is3D", void 0);
  28262. __decorate([
  28263. BABYLON.serialize()
  28264. ], BaseTexture.prototype, "gammaSpace", void 0);
  28265. __decorate([
  28266. BABYLON.serialize()
  28267. ], BaseTexture.prototype, "invertZ", void 0);
  28268. __decorate([
  28269. BABYLON.serialize()
  28270. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  28271. __decorate([
  28272. BABYLON.serialize()
  28273. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  28274. __decorate([
  28275. BABYLON.serialize()
  28276. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  28277. __decorate([
  28278. BABYLON.serialize()
  28279. ], BaseTexture.prototype, "isRenderTarget", void 0);
  28280. return BaseTexture;
  28281. }());
  28282. BABYLON.BaseTexture = BaseTexture;
  28283. })(BABYLON || (BABYLON = {}));
  28284. //# sourceMappingURL=babylon.baseTexture.js.map
  28285. "use strict";
  28286. var BABYLON;
  28287. (function (BABYLON) {
  28288. var Texture = /** @class */ (function (_super) {
  28289. __extends(Texture, _super);
  28290. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  28291. if (noMipmap === void 0) { noMipmap = false; }
  28292. if (invertY === void 0) { invertY = true; }
  28293. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28294. if (onLoad === void 0) { onLoad = null; }
  28295. if (onError === void 0) { onError = null; }
  28296. if (buffer === void 0) { buffer = null; }
  28297. if (deleteBuffer === void 0) { deleteBuffer = false; }
  28298. var _this = _super.call(this, scene) || this;
  28299. _this.uOffset = 0;
  28300. _this.vOffset = 0;
  28301. _this.uScale = 1.0;
  28302. _this.vScale = 1.0;
  28303. _this.uAng = 0;
  28304. _this.vAng = 0;
  28305. _this.wAng = 0;
  28306. _this._isBlocking = true;
  28307. _this.name = url || "";
  28308. _this.url = url;
  28309. _this._noMipmap = noMipmap;
  28310. _this._invertY = invertY;
  28311. _this._samplingMode = samplingMode;
  28312. _this._buffer = buffer;
  28313. _this._deleteBuffer = deleteBuffer;
  28314. if (format) {
  28315. _this._format = format;
  28316. }
  28317. scene = _this.getScene();
  28318. if (!scene) {
  28319. return _this;
  28320. }
  28321. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  28322. var load = function () {
  28323. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  28324. _this.onLoadObservable.notifyObservers(_this);
  28325. }
  28326. if (onLoad) {
  28327. onLoad();
  28328. }
  28329. if (!_this.isBlocking && scene) {
  28330. scene.resetCachedMaterial();
  28331. }
  28332. };
  28333. if (!_this.url) {
  28334. _this._delayedOnLoad = load;
  28335. _this._delayedOnError = onError;
  28336. return _this;
  28337. }
  28338. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  28339. if (!_this._texture) {
  28340. if (!scene.useDelayedTextureLoading) {
  28341. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  28342. if (deleteBuffer) {
  28343. delete _this._buffer;
  28344. }
  28345. }
  28346. else {
  28347. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28348. _this._delayedOnLoad = load;
  28349. _this._delayedOnError = onError;
  28350. }
  28351. }
  28352. else {
  28353. if (_this._texture.isReady) {
  28354. BABYLON.Tools.SetImmediate(function () { return load(); });
  28355. }
  28356. else {
  28357. _this._texture.onLoadedObservable.add(load);
  28358. }
  28359. }
  28360. return _this;
  28361. }
  28362. Object.defineProperty(Texture.prototype, "noMipmap", {
  28363. get: function () {
  28364. return this._noMipmap;
  28365. },
  28366. enumerable: true,
  28367. configurable: true
  28368. });
  28369. Object.defineProperty(Texture.prototype, "isBlocking", {
  28370. get: function () {
  28371. return this._isBlocking;
  28372. },
  28373. set: function (value) {
  28374. this._isBlocking = value;
  28375. },
  28376. enumerable: true,
  28377. configurable: true
  28378. });
  28379. Object.defineProperty(Texture.prototype, "samplingMode", {
  28380. get: function () {
  28381. return this._samplingMode;
  28382. },
  28383. enumerable: true,
  28384. configurable: true
  28385. });
  28386. Texture.prototype.updateURL = function (url) {
  28387. this.url = url;
  28388. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28389. this.delayLoad();
  28390. };
  28391. Texture.prototype.delayLoad = function () {
  28392. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28393. return;
  28394. }
  28395. var scene = this.getScene();
  28396. if (!scene) {
  28397. return;
  28398. }
  28399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28400. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  28401. if (!this._texture) {
  28402. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  28403. if (this._deleteBuffer) {
  28404. delete this._buffer;
  28405. }
  28406. }
  28407. else {
  28408. if (this._delayedOnLoad) {
  28409. if (this._texture.isReady) {
  28410. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  28411. }
  28412. else {
  28413. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  28414. }
  28415. }
  28416. }
  28417. this._delayedOnLoad = null;
  28418. this._delayedOnError = null;
  28419. };
  28420. Texture.prototype.updateSamplingMode = function (samplingMode) {
  28421. if (!this._texture) {
  28422. return;
  28423. }
  28424. var scene = this.getScene();
  28425. if (!scene) {
  28426. return;
  28427. }
  28428. this._samplingMode = samplingMode;
  28429. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  28430. };
  28431. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  28432. x *= this.uScale;
  28433. y *= this.vScale;
  28434. x -= 0.5 * this.uScale;
  28435. y -= 0.5 * this.vScale;
  28436. z -= 0.5;
  28437. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  28438. t.x += 0.5 * this.uScale + this.uOffset;
  28439. t.y += 0.5 * this.vScale + this.vOffset;
  28440. t.z += 0.5;
  28441. };
  28442. Texture.prototype.getTextureMatrix = function () {
  28443. var _this = this;
  28444. if (this.uOffset === this._cachedUOffset &&
  28445. this.vOffset === this._cachedVOffset &&
  28446. this.uScale === this._cachedUScale &&
  28447. this.vScale === this._cachedVScale &&
  28448. this.uAng === this._cachedUAng &&
  28449. this.vAng === this._cachedVAng &&
  28450. this.wAng === this._cachedWAng) {
  28451. return this._cachedTextureMatrix;
  28452. }
  28453. this._cachedUOffset = this.uOffset;
  28454. this._cachedVOffset = this.vOffset;
  28455. this._cachedUScale = this.uScale;
  28456. this._cachedVScale = this.vScale;
  28457. this._cachedUAng = this.uAng;
  28458. this._cachedVAng = this.vAng;
  28459. this._cachedWAng = this.wAng;
  28460. if (!this._cachedTextureMatrix) {
  28461. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  28462. this._rowGenerationMatrix = new BABYLON.Matrix();
  28463. this._t0 = BABYLON.Vector3.Zero();
  28464. this._t1 = BABYLON.Vector3.Zero();
  28465. this._t2 = BABYLON.Vector3.Zero();
  28466. }
  28467. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  28468. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  28469. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  28470. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  28471. this._t1.subtractInPlace(this._t0);
  28472. this._t2.subtractInPlace(this._t0);
  28473. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28474. this._cachedTextureMatrix.m[0] = this._t1.x;
  28475. this._cachedTextureMatrix.m[1] = this._t1.y;
  28476. this._cachedTextureMatrix.m[2] = this._t1.z;
  28477. this._cachedTextureMatrix.m[4] = this._t2.x;
  28478. this._cachedTextureMatrix.m[5] = this._t2.y;
  28479. this._cachedTextureMatrix.m[6] = this._t2.z;
  28480. this._cachedTextureMatrix.m[8] = this._t0.x;
  28481. this._cachedTextureMatrix.m[9] = this._t0.y;
  28482. this._cachedTextureMatrix.m[10] = this._t0.z;
  28483. var scene = this.getScene();
  28484. if (!scene) {
  28485. return this._cachedTextureMatrix;
  28486. }
  28487. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  28488. return mat.hasTexture(_this);
  28489. });
  28490. return this._cachedTextureMatrix;
  28491. };
  28492. Texture.prototype.getReflectionTextureMatrix = function () {
  28493. var _this = this;
  28494. var scene = this.getScene();
  28495. if (!scene) {
  28496. return this._cachedTextureMatrix;
  28497. }
  28498. if (this.uOffset === this._cachedUOffset &&
  28499. this.vOffset === this._cachedVOffset &&
  28500. this.uScale === this._cachedUScale &&
  28501. this.vScale === this._cachedVScale &&
  28502. this.coordinatesMode === this._cachedCoordinatesMode) {
  28503. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  28504. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  28505. return this._cachedTextureMatrix;
  28506. }
  28507. }
  28508. else {
  28509. return this._cachedTextureMatrix;
  28510. }
  28511. }
  28512. if (!this._cachedTextureMatrix) {
  28513. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  28514. }
  28515. if (!this._projectionModeMatrix) {
  28516. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  28517. }
  28518. this._cachedUOffset = this.uOffset;
  28519. this._cachedVOffset = this.vOffset;
  28520. this._cachedUScale = this.uScale;
  28521. this._cachedVScale = this.vScale;
  28522. this._cachedCoordinatesMode = this.coordinatesMode;
  28523. switch (this.coordinatesMode) {
  28524. case Texture.PLANAR_MODE:
  28525. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28526. this._cachedTextureMatrix[0] = this.uScale;
  28527. this._cachedTextureMatrix[5] = this.vScale;
  28528. this._cachedTextureMatrix[12] = this.uOffset;
  28529. this._cachedTextureMatrix[13] = this.vOffset;
  28530. break;
  28531. case Texture.PROJECTION_MODE:
  28532. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  28533. this._projectionModeMatrix.m[0] = 0.5;
  28534. this._projectionModeMatrix.m[5] = -0.5;
  28535. this._projectionModeMatrix.m[10] = 0.0;
  28536. this._projectionModeMatrix.m[12] = 0.5;
  28537. this._projectionModeMatrix.m[13] = 0.5;
  28538. this._projectionModeMatrix.m[14] = 1.0;
  28539. this._projectionModeMatrix.m[15] = 1.0;
  28540. var projectionMatrix = scene.getProjectionMatrix();
  28541. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  28542. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  28543. break;
  28544. default:
  28545. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28546. break;
  28547. }
  28548. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  28549. return (mat.getActiveTextures().indexOf(_this) !== -1);
  28550. });
  28551. return this._cachedTextureMatrix;
  28552. };
  28553. Texture.prototype.clone = function () {
  28554. var _this = this;
  28555. return BABYLON.SerializationHelper.Clone(function () {
  28556. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  28557. }, this);
  28558. };
  28559. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  28560. get: function () {
  28561. if (!this._onLoadObservable) {
  28562. this._onLoadObservable = new BABYLON.Observable();
  28563. }
  28564. return this._onLoadObservable;
  28565. },
  28566. enumerable: true,
  28567. configurable: true
  28568. });
  28569. Texture.prototype.serialize = function () {
  28570. var serializationObject = _super.prototype.serialize.call(this);
  28571. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  28572. serializationObject.base64String = this._buffer;
  28573. serializationObject.name = serializationObject.name.replace("data:", "");
  28574. }
  28575. return serializationObject;
  28576. };
  28577. Texture.prototype.getClassName = function () {
  28578. return "Texture";
  28579. };
  28580. Texture.prototype.dispose = function () {
  28581. _super.prototype.dispose.call(this);
  28582. if (this.onLoadObservable) {
  28583. this.onLoadObservable.clear();
  28584. this._onLoadObservable = null;
  28585. }
  28586. this._delayedOnLoad = null;
  28587. this._delayedOnError = null;
  28588. };
  28589. // Statics
  28590. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  28591. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28592. if (onLoad === void 0) { onLoad = null; }
  28593. if (onError === void 0) { onError = null; }
  28594. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28595. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  28596. };
  28597. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  28598. if (parsedTexture.customType) {
  28599. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  28600. // Update Sampling Mode
  28601. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  28602. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  28603. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  28604. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  28605. }
  28606. }
  28607. return parsedCustomTexture;
  28608. }
  28609. if (parsedTexture.isCube) {
  28610. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  28611. }
  28612. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  28613. return null;
  28614. }
  28615. var texture = BABYLON.SerializationHelper.Parse(function () {
  28616. var generateMipMaps = true;
  28617. if (parsedTexture.noMipmap) {
  28618. generateMipMaps = false;
  28619. }
  28620. if (parsedTexture.mirrorPlane) {
  28621. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  28622. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  28623. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  28624. return mirrorTexture;
  28625. }
  28626. else if (parsedTexture.isRenderTarget) {
  28627. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  28628. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  28629. return renderTargetTexture;
  28630. }
  28631. else {
  28632. var texture;
  28633. if (parsedTexture.base64String) {
  28634. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  28635. }
  28636. else {
  28637. var url = rootUrl + parsedTexture.name;
  28638. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  28639. url = parsedTexture.url;
  28640. }
  28641. texture = new Texture(url, scene, !generateMipMaps);
  28642. }
  28643. return texture;
  28644. }
  28645. }, parsedTexture, scene);
  28646. // Update Sampling Mode
  28647. if (parsedTexture.samplingMode) {
  28648. var sampling = parsedTexture.samplingMode;
  28649. if (texture._samplingMode !== sampling) {
  28650. texture.updateSamplingMode(sampling);
  28651. }
  28652. }
  28653. // Animations
  28654. if (parsedTexture.animations) {
  28655. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  28656. var parsedAnimation = parsedTexture.animations[animationIndex];
  28657. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28658. }
  28659. }
  28660. return texture;
  28661. };
  28662. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  28663. if (deleteBuffer === void 0) { deleteBuffer = false; }
  28664. if (noMipmap === void 0) { noMipmap = false; }
  28665. if (invertY === void 0) { invertY = true; }
  28666. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28667. if (onLoad === void 0) { onLoad = null; }
  28668. if (onError === void 0) { onError = null; }
  28669. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28670. if (name.substr(0, 5) !== "data:") {
  28671. name = "data:" + name;
  28672. }
  28673. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  28674. };
  28675. // Constants
  28676. Texture.NEAREST_SAMPLINGMODE = 1;
  28677. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  28678. Texture.BILINEAR_SAMPLINGMODE = 2;
  28679. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  28680. Texture.TRILINEAR_SAMPLINGMODE = 3;
  28681. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  28682. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  28683. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  28684. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  28685. Texture.NEAREST_LINEAR = 7;
  28686. Texture.NEAREST_NEAREST = 8;
  28687. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  28688. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  28689. Texture.LINEAR_LINEAR = 11;
  28690. Texture.LINEAR_NEAREST = 12;
  28691. Texture.EXPLICIT_MODE = 0;
  28692. Texture.SPHERICAL_MODE = 1;
  28693. Texture.PLANAR_MODE = 2;
  28694. Texture.CUBIC_MODE = 3;
  28695. Texture.PROJECTION_MODE = 4;
  28696. Texture.SKYBOX_MODE = 5;
  28697. Texture.INVCUBIC_MODE = 6;
  28698. Texture.EQUIRECTANGULAR_MODE = 7;
  28699. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  28700. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  28701. Texture.CLAMP_ADDRESSMODE = 0;
  28702. Texture.WRAP_ADDRESSMODE = 1;
  28703. Texture.MIRROR_ADDRESSMODE = 2;
  28704. /**
  28705. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  28706. */
  28707. Texture.UseSerializedUrlIfAny = false;
  28708. __decorate([
  28709. BABYLON.serialize()
  28710. ], Texture.prototype, "url", void 0);
  28711. __decorate([
  28712. BABYLON.serialize()
  28713. ], Texture.prototype, "uOffset", void 0);
  28714. __decorate([
  28715. BABYLON.serialize()
  28716. ], Texture.prototype, "vOffset", void 0);
  28717. __decorate([
  28718. BABYLON.serialize()
  28719. ], Texture.prototype, "uScale", void 0);
  28720. __decorate([
  28721. BABYLON.serialize()
  28722. ], Texture.prototype, "vScale", void 0);
  28723. __decorate([
  28724. BABYLON.serialize()
  28725. ], Texture.prototype, "uAng", void 0);
  28726. __decorate([
  28727. BABYLON.serialize()
  28728. ], Texture.prototype, "vAng", void 0);
  28729. __decorate([
  28730. BABYLON.serialize()
  28731. ], Texture.prototype, "wAng", void 0);
  28732. __decorate([
  28733. BABYLON.serialize()
  28734. ], Texture.prototype, "isBlocking", null);
  28735. return Texture;
  28736. }(BABYLON.BaseTexture));
  28737. BABYLON.Texture = Texture;
  28738. })(BABYLON || (BABYLON = {}));
  28739. //# sourceMappingURL=babylon.texture.js.map
  28740. "use strict";
  28741. var BABYLON;
  28742. (function (BABYLON) {
  28743. var _InstancesBatch = /** @class */ (function () {
  28744. function _InstancesBatch() {
  28745. this.mustReturn = false;
  28746. this.visibleInstances = new Array();
  28747. this.renderSelf = new Array();
  28748. }
  28749. return _InstancesBatch;
  28750. }());
  28751. BABYLON._InstancesBatch = _InstancesBatch;
  28752. var Mesh = /** @class */ (function (_super) {
  28753. __extends(Mesh, _super);
  28754. /**
  28755. * @constructor
  28756. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  28757. * @param {Scene} scene The scene to add this mesh to.
  28758. * @param {Node} parent The parent of this mesh, if it has one
  28759. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  28760. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  28761. * When false, achieved by calling a clone(), also passing False.
  28762. * This will make creation of children, recursive.
  28763. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  28764. */
  28765. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  28766. if (scene === void 0) { scene = null; }
  28767. if (parent === void 0) { parent = null; }
  28768. if (source === void 0) { source = null; }
  28769. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28770. var _this = _super.call(this, name, scene) || this;
  28771. // Events
  28772. /**
  28773. * An event triggered before rendering the mesh
  28774. */
  28775. _this.onBeforeRenderObservable = new BABYLON.Observable();
  28776. /**
  28777. * An event triggered after rendering the mesh
  28778. */
  28779. _this.onAfterRenderObservable = new BABYLON.Observable();
  28780. /**
  28781. * An event triggered before drawing the mesh
  28782. */
  28783. _this.onBeforeDrawObservable = new BABYLON.Observable();
  28784. // Members
  28785. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28786. _this.instances = new Array();
  28787. _this._LODLevels = new Array();
  28788. _this._visibleInstances = {};
  28789. _this._renderIdForInstances = new Array();
  28790. _this._batchCache = new _InstancesBatch();
  28791. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  28792. // Use by builder only to know what orientation were the mesh build in.
  28793. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  28794. _this.overrideMaterialSideOrientation = null;
  28795. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  28796. // Will be used to save a source mesh reference, If any
  28797. _this._source = null;
  28798. scene = _this.getScene();
  28799. if (source) {
  28800. // Source mesh
  28801. _this._source = source;
  28802. // Geometry
  28803. if (source._geometry) {
  28804. source._geometry.applyToMesh(_this);
  28805. }
  28806. // Deep copy
  28807. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  28808. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  28809. // Metadata
  28810. if (source.metadata && source.metadata.clone) {
  28811. _this.metadata = source.metadata.clone();
  28812. }
  28813. else {
  28814. _this.metadata = source.metadata;
  28815. }
  28816. // Tags
  28817. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  28818. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  28819. }
  28820. // Parent
  28821. _this.parent = source.parent;
  28822. // Pivot
  28823. _this.setPivotMatrix(source.getPivotMatrix());
  28824. _this.id = name + "." + source.id;
  28825. // Material
  28826. _this.material = source.material;
  28827. var index;
  28828. if (!doNotCloneChildren) {
  28829. // Children
  28830. var directDescendants = source.getDescendants(true);
  28831. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  28832. var child = directDescendants[index_1];
  28833. if (child.clone) {
  28834. child.clone(name + "." + child.name, _this);
  28835. }
  28836. }
  28837. }
  28838. // Physics clone
  28839. var physicsEngine = _this.getScene().getPhysicsEngine();
  28840. if (clonePhysicsImpostor && physicsEngine) {
  28841. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  28842. if (impostor) {
  28843. _this.physicsImpostor = impostor.clone(_this);
  28844. }
  28845. }
  28846. // Particles
  28847. for (index = 0; index < scene.particleSystems.length; index++) {
  28848. var system = scene.particleSystems[index];
  28849. if (system.emitter === source) {
  28850. system.clone(system.name, _this);
  28851. }
  28852. }
  28853. _this.computeWorldMatrix(true);
  28854. }
  28855. // Parent
  28856. if (parent !== null) {
  28857. _this.parent = parent;
  28858. }
  28859. return _this;
  28860. }
  28861. Object.defineProperty(Mesh, "FRONTSIDE", {
  28862. /**
  28863. * Mesh side orientation : usually the external or front surface
  28864. */
  28865. get: function () {
  28866. return Mesh._FRONTSIDE;
  28867. },
  28868. enumerable: true,
  28869. configurable: true
  28870. });
  28871. Object.defineProperty(Mesh, "BACKSIDE", {
  28872. /**
  28873. * Mesh side orientation : usually the internal or back surface
  28874. */
  28875. get: function () {
  28876. return Mesh._BACKSIDE;
  28877. },
  28878. enumerable: true,
  28879. configurable: true
  28880. });
  28881. Object.defineProperty(Mesh, "DOUBLESIDE", {
  28882. /**
  28883. * Mesh side orientation : both internal and external or front and back surfaces
  28884. */
  28885. get: function () {
  28886. return Mesh._DOUBLESIDE;
  28887. },
  28888. enumerable: true,
  28889. configurable: true
  28890. });
  28891. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  28892. /**
  28893. * Mesh side orientation : by default, `FRONTSIDE`
  28894. */
  28895. get: function () {
  28896. return Mesh._DEFAULTSIDE;
  28897. },
  28898. enumerable: true,
  28899. configurable: true
  28900. });
  28901. Object.defineProperty(Mesh, "NO_CAP", {
  28902. /**
  28903. * Mesh cap setting : no cap
  28904. */
  28905. get: function () {
  28906. return Mesh._NO_CAP;
  28907. },
  28908. enumerable: true,
  28909. configurable: true
  28910. });
  28911. Object.defineProperty(Mesh, "CAP_START", {
  28912. /**
  28913. * Mesh cap setting : one cap at the beginning of the mesh
  28914. */
  28915. get: function () {
  28916. return Mesh._CAP_START;
  28917. },
  28918. enumerable: true,
  28919. configurable: true
  28920. });
  28921. Object.defineProperty(Mesh, "CAP_END", {
  28922. /**
  28923. * Mesh cap setting : one cap at the end of the mesh
  28924. */
  28925. get: function () {
  28926. return Mesh._CAP_END;
  28927. },
  28928. enumerable: true,
  28929. configurable: true
  28930. });
  28931. Object.defineProperty(Mesh, "CAP_ALL", {
  28932. /**
  28933. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  28934. */
  28935. get: function () {
  28936. return Mesh._CAP_ALL;
  28937. },
  28938. enumerable: true,
  28939. configurable: true
  28940. });
  28941. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  28942. set: function (callback) {
  28943. if (this._onBeforeDrawObserver) {
  28944. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  28945. }
  28946. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  28947. },
  28948. enumerable: true,
  28949. configurable: true
  28950. });
  28951. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  28952. get: function () {
  28953. return this._morphTargetManager;
  28954. },
  28955. set: function (value) {
  28956. if (this._morphTargetManager === value) {
  28957. return;
  28958. }
  28959. this._morphTargetManager = value;
  28960. this._syncGeometryWithMorphTargetManager();
  28961. },
  28962. enumerable: true,
  28963. configurable: true
  28964. });
  28965. Object.defineProperty(Mesh.prototype, "source", {
  28966. get: function () {
  28967. return this._source;
  28968. },
  28969. enumerable: true,
  28970. configurable: true
  28971. });
  28972. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  28973. get: function () {
  28974. return this._unIndexed;
  28975. },
  28976. set: function (value) {
  28977. if (this._unIndexed !== value) {
  28978. this._unIndexed = value;
  28979. this._markSubMeshesAsAttributesDirty();
  28980. }
  28981. },
  28982. enumerable: true,
  28983. configurable: true
  28984. });
  28985. // Methods
  28986. /**
  28987. * Returns the string "Mesh".
  28988. */
  28989. Mesh.prototype.getClassName = function () {
  28990. return "Mesh";
  28991. };
  28992. /**
  28993. * Returns a string.
  28994. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28995. */
  28996. Mesh.prototype.toString = function (fullDetails) {
  28997. var ret = _super.prototype.toString.call(this, fullDetails);
  28998. ret += ", n vertices: " + this.getTotalVertices();
  28999. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  29000. if (this.animations) {
  29001. for (var i = 0; i < this.animations.length; i++) {
  29002. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  29003. }
  29004. }
  29005. if (fullDetails) {
  29006. if (this._geometry) {
  29007. var ib = this.getIndices();
  29008. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29009. if (vb && ib) {
  29010. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  29011. }
  29012. }
  29013. else {
  29014. ret += ", flat shading: UNKNOWN";
  29015. }
  29016. }
  29017. return ret;
  29018. };
  29019. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  29020. /**
  29021. * True if the mesh has some Levels Of Details (LOD).
  29022. * Returns a boolean.
  29023. */
  29024. get: function () {
  29025. return this._LODLevels.length > 0;
  29026. },
  29027. enumerable: true,
  29028. configurable: true
  29029. });
  29030. /**
  29031. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  29032. * @returns an array of {BABYLON.MeshLODLevel}
  29033. */
  29034. Mesh.prototype.getLODLevels = function () {
  29035. return this._LODLevels;
  29036. };
  29037. Mesh.prototype._sortLODLevels = function () {
  29038. this._LODLevels.sort(function (a, b) {
  29039. if (a.distance < b.distance) {
  29040. return 1;
  29041. }
  29042. if (a.distance > b.distance) {
  29043. return -1;
  29044. }
  29045. return 0;
  29046. });
  29047. };
  29048. /**
  29049. * Add a mesh as LOD level triggered at the given distance.
  29050. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  29051. * @param {number} distance The distance from the center of the object to show this level
  29052. * @param {Mesh} mesh The mesh to be added as LOD level
  29053. * @return {Mesh} This mesh (for chaining)
  29054. */
  29055. Mesh.prototype.addLODLevel = function (distance, mesh) {
  29056. if (mesh && mesh._masterMesh) {
  29057. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  29058. return this;
  29059. }
  29060. var level = new BABYLON.MeshLODLevel(distance, mesh);
  29061. this._LODLevels.push(level);
  29062. if (mesh) {
  29063. mesh._masterMesh = this;
  29064. }
  29065. this._sortLODLevels();
  29066. return this;
  29067. };
  29068. /**
  29069. * Returns the LOD level mesh at the passed distance or null if not found.
  29070. * It is related to the method `addLODLevel(distance, mesh)`.
  29071. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  29072. * Returns an object Mesh or `null`.
  29073. */
  29074. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  29075. for (var index = 0; index < this._LODLevels.length; index++) {
  29076. var level = this._LODLevels[index];
  29077. if (level.distance === distance) {
  29078. return level.mesh;
  29079. }
  29080. }
  29081. return null;
  29082. };
  29083. /**
  29084. * Remove a mesh from the LOD array
  29085. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  29086. * @param {Mesh} mesh The mesh to be removed.
  29087. * @return {Mesh} This mesh (for chaining)
  29088. */
  29089. Mesh.prototype.removeLODLevel = function (mesh) {
  29090. for (var index = 0; index < this._LODLevels.length; index++) {
  29091. if (this._LODLevels[index].mesh === mesh) {
  29092. this._LODLevels.splice(index, 1);
  29093. if (mesh) {
  29094. mesh._masterMesh = null;
  29095. }
  29096. }
  29097. }
  29098. this._sortLODLevels();
  29099. return this;
  29100. };
  29101. /**
  29102. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  29103. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  29104. */
  29105. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  29106. if (!this._LODLevels || this._LODLevels.length === 0) {
  29107. return this;
  29108. }
  29109. var bSphere;
  29110. if (boundingSphere) {
  29111. bSphere = boundingSphere;
  29112. }
  29113. else {
  29114. var boundingInfo = this.getBoundingInfo();
  29115. bSphere = boundingInfo.boundingSphere;
  29116. }
  29117. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  29118. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  29119. if (this.onLODLevelSelection) {
  29120. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  29121. }
  29122. return this;
  29123. }
  29124. for (var index = 0; index < this._LODLevels.length; index++) {
  29125. var level = this._LODLevels[index];
  29126. if (level.distance < distanceToCamera) {
  29127. if (level.mesh) {
  29128. level.mesh._preActivate();
  29129. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  29130. }
  29131. if (this.onLODLevelSelection) {
  29132. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  29133. }
  29134. return level.mesh;
  29135. }
  29136. }
  29137. if (this.onLODLevelSelection) {
  29138. this.onLODLevelSelection(distanceToCamera, this, this);
  29139. }
  29140. return this;
  29141. };
  29142. Object.defineProperty(Mesh.prototype, "geometry", {
  29143. /**
  29144. * Returns the mesh internal Geometry object.
  29145. */
  29146. get: function () {
  29147. return this._geometry;
  29148. },
  29149. enumerable: true,
  29150. configurable: true
  29151. });
  29152. /**
  29153. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  29154. */
  29155. Mesh.prototype.getTotalVertices = function () {
  29156. if (this._geometry === null || this._geometry === undefined) {
  29157. return 0;
  29158. }
  29159. return this._geometry.getTotalVertices();
  29160. };
  29161. /**
  29162. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  29163. * 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.
  29164. * You can force the copy with forceCopy === true
  29165. * Returns null if the mesh has no geometry or no vertex buffer.
  29166. * Possible `kind` values :
  29167. * - BABYLON.VertexBuffer.PositionKind
  29168. * - BABYLON.VertexBuffer.UVKind
  29169. * - BABYLON.VertexBuffer.UV2Kind
  29170. * - BABYLON.VertexBuffer.UV3Kind
  29171. * - BABYLON.VertexBuffer.UV4Kind
  29172. * - BABYLON.VertexBuffer.UV5Kind
  29173. * - BABYLON.VertexBuffer.UV6Kind
  29174. * - BABYLON.VertexBuffer.ColorKind
  29175. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29176. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29177. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29178. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29179. */
  29180. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29181. if (!this._geometry) {
  29182. return null;
  29183. }
  29184. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  29185. };
  29186. /**
  29187. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  29188. * Returns `null` if the mesh has no geometry.
  29189. * Possible `kind` values :
  29190. * - BABYLON.VertexBuffer.PositionKind
  29191. * - BABYLON.VertexBuffer.UVKind
  29192. * - BABYLON.VertexBuffer.UV2Kind
  29193. * - BABYLON.VertexBuffer.UV3Kind
  29194. * - BABYLON.VertexBuffer.UV4Kind
  29195. * - BABYLON.VertexBuffer.UV5Kind
  29196. * - BABYLON.VertexBuffer.UV6Kind
  29197. * - BABYLON.VertexBuffer.ColorKind
  29198. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29199. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29200. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29201. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29202. */
  29203. Mesh.prototype.getVertexBuffer = function (kind) {
  29204. if (!this._geometry) {
  29205. return null;
  29206. }
  29207. return this._geometry.getVertexBuffer(kind);
  29208. };
  29209. /**
  29210. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  29211. * Possible `kind` values :
  29212. * - BABYLON.VertexBuffer.PositionKind
  29213. * - BABYLON.VertexBuffer.UVKind
  29214. * - BABYLON.VertexBuffer.UV2Kind
  29215. * - BABYLON.VertexBuffer.UV3Kind
  29216. * - BABYLON.VertexBuffer.UV4Kind
  29217. * - BABYLON.VertexBuffer.UV5Kind
  29218. * - BABYLON.VertexBuffer.UV6Kind
  29219. * - BABYLON.VertexBuffer.ColorKind
  29220. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29221. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29222. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29223. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29224. */
  29225. Mesh.prototype.isVerticesDataPresent = function (kind) {
  29226. if (!this._geometry) {
  29227. if (this._delayInfo) {
  29228. return this._delayInfo.indexOf(kind) !== -1;
  29229. }
  29230. return false;
  29231. }
  29232. return this._geometry.isVerticesDataPresent(kind);
  29233. };
  29234. /**
  29235. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  29236. * Possible `kind` values :
  29237. * - BABYLON.VertexBuffer.PositionKind
  29238. * - BABYLON.VertexBuffer.UVKind
  29239. * - BABYLON.VertexBuffer.UV2Kind
  29240. * - BABYLON.VertexBuffer.UV3Kind
  29241. * - BABYLON.VertexBuffer.UV4Kind
  29242. * - BABYLON.VertexBuffer.UV5Kind
  29243. * - BABYLON.VertexBuffer.UV6Kind
  29244. * - BABYLON.VertexBuffer.ColorKind
  29245. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29246. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29247. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29248. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29249. */
  29250. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  29251. if (!this._geometry) {
  29252. if (this._delayInfo) {
  29253. return this._delayInfo.indexOf(kind) !== -1;
  29254. }
  29255. return false;
  29256. }
  29257. return this._geometry.isVertexBufferUpdatable(kind);
  29258. };
  29259. /**
  29260. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  29261. * Possible `kind` values :
  29262. * - BABYLON.VertexBuffer.PositionKind
  29263. * - BABYLON.VertexBuffer.UVKind
  29264. * - BABYLON.VertexBuffer.UV2Kind
  29265. * - BABYLON.VertexBuffer.UV3Kind
  29266. * - BABYLON.VertexBuffer.UV4Kind
  29267. * - BABYLON.VertexBuffer.UV5Kind
  29268. * - BABYLON.VertexBuffer.UV6Kind
  29269. * - BABYLON.VertexBuffer.ColorKind
  29270. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29271. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29272. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29273. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29274. */
  29275. Mesh.prototype.getVerticesDataKinds = function () {
  29276. if (!this._geometry) {
  29277. var result = new Array();
  29278. if (this._delayInfo) {
  29279. this._delayInfo.forEach(function (kind, index, array) {
  29280. result.push(kind);
  29281. });
  29282. }
  29283. return result;
  29284. }
  29285. return this._geometry.getVerticesDataKinds();
  29286. };
  29287. /**
  29288. * Returns a positive integer : the total number of indices in this mesh geometry.
  29289. * Returns zero if the mesh has no geometry.
  29290. */
  29291. Mesh.prototype.getTotalIndices = function () {
  29292. if (!this._geometry) {
  29293. return 0;
  29294. }
  29295. return this._geometry.getTotalIndices();
  29296. };
  29297. /**
  29298. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  29299. * 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.
  29300. * Returns an empty array if the mesh has no geometry.
  29301. */
  29302. Mesh.prototype.getIndices = function (copyWhenShared) {
  29303. if (!this._geometry) {
  29304. return [];
  29305. }
  29306. return this._geometry.getIndices(copyWhenShared);
  29307. };
  29308. Object.defineProperty(Mesh.prototype, "isBlocked", {
  29309. get: function () {
  29310. return this._masterMesh !== null && this._masterMesh !== undefined;
  29311. },
  29312. enumerable: true,
  29313. configurable: true
  29314. });
  29315. /**
  29316. * Determine if the current mesh is ready to be rendered
  29317. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  29318. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  29319. * @returns true if all associated assets are ready (material, textures, shaders)
  29320. */
  29321. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  29322. if (completeCheck === void 0) { completeCheck = false; }
  29323. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  29324. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29325. return false;
  29326. }
  29327. if (!_super.prototype.isReady.call(this, completeCheck)) {
  29328. return false;
  29329. }
  29330. if (!this.subMeshes || this.subMeshes.length === 0) {
  29331. return true;
  29332. }
  29333. if (!completeCheck) {
  29334. return true;
  29335. }
  29336. var engine = this.getEngine();
  29337. var scene = this.getScene();
  29338. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  29339. this.computeWorldMatrix();
  29340. var mat = this.material || scene.defaultMaterial;
  29341. if (mat) {
  29342. if (mat.storeEffectOnSubMeshes) {
  29343. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  29344. var subMesh = _a[_i];
  29345. var effectiveMaterial = subMesh.getMaterial();
  29346. if (effectiveMaterial) {
  29347. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29348. return false;
  29349. }
  29350. }
  29351. }
  29352. }
  29353. else {
  29354. if (!mat.isReady(this, hardwareInstancedRendering)) {
  29355. return false;
  29356. }
  29357. }
  29358. }
  29359. // Shadows
  29360. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  29361. var light = _c[_b];
  29362. var generator = light.getShadowGenerator();
  29363. if (generator) {
  29364. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  29365. var subMesh = _e[_d];
  29366. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  29367. return false;
  29368. }
  29369. }
  29370. }
  29371. }
  29372. // LOD
  29373. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  29374. var lod = _g[_f];
  29375. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  29376. return false;
  29377. }
  29378. }
  29379. return true;
  29380. };
  29381. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  29382. /**
  29383. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  29384. * This property is pertinent only for updatable parametric shapes.
  29385. */
  29386. get: function () {
  29387. return this._areNormalsFrozen;
  29388. },
  29389. enumerable: true,
  29390. configurable: true
  29391. });
  29392. /**
  29393. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  29394. * It has no effect at all on other shapes.
  29395. * It prevents the mesh normals from being recomputed on next `positions` array update.
  29396. * Returns the Mesh.
  29397. */
  29398. Mesh.prototype.freezeNormals = function () {
  29399. this._areNormalsFrozen = true;
  29400. return this;
  29401. };
  29402. /**
  29403. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  29404. * It has no effect at all on other shapes.
  29405. * It reactivates the mesh normals computation if it was previously frozen.
  29406. * Returns the Mesh.
  29407. */
  29408. Mesh.prototype.unfreezeNormals = function () {
  29409. this._areNormalsFrozen = false;
  29410. return this;
  29411. };
  29412. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  29413. /**
  29414. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  29415. */
  29416. set: function (count) {
  29417. this._overridenInstanceCount = count;
  29418. },
  29419. enumerable: true,
  29420. configurable: true
  29421. });
  29422. // Methods
  29423. Mesh.prototype._preActivate = function () {
  29424. var sceneRenderId = this.getScene().getRenderId();
  29425. if (this._preActivateId === sceneRenderId) {
  29426. return this;
  29427. }
  29428. this._preActivateId = sceneRenderId;
  29429. this._visibleInstances = null;
  29430. return this;
  29431. };
  29432. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  29433. if (this._visibleInstances) {
  29434. this._visibleInstances.intermediateDefaultRenderId = renderId;
  29435. }
  29436. return this;
  29437. };
  29438. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  29439. if (!this._visibleInstances) {
  29440. this._visibleInstances = {};
  29441. this._visibleInstances.defaultRenderId = renderId;
  29442. this._visibleInstances.selfDefaultRenderId = this._renderId;
  29443. }
  29444. if (!this._visibleInstances[renderId]) {
  29445. this._visibleInstances[renderId] = new Array();
  29446. }
  29447. this._visibleInstances[renderId].push(instance);
  29448. return this;
  29449. };
  29450. /**
  29451. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  29452. * This means the mesh underlying bounding box and sphere are recomputed.
  29453. * Returns the Mesh.
  29454. */
  29455. Mesh.prototype.refreshBoundingInfo = function () {
  29456. return this._refreshBoundingInfo(false);
  29457. };
  29458. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  29459. if (this._boundingInfo && this._boundingInfo.isLocked) {
  29460. return this;
  29461. }
  29462. var data = this._getPositionData(applySkeleton);
  29463. if (data) {
  29464. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  29465. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29466. }
  29467. if (this.subMeshes) {
  29468. for (var index = 0; index < this.subMeshes.length; index++) {
  29469. this.subMeshes[index].refreshBoundingInfo();
  29470. }
  29471. }
  29472. this._updateBoundingInfo();
  29473. return this;
  29474. };
  29475. Mesh.prototype._getPositionData = function (applySkeleton) {
  29476. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29477. if (data && applySkeleton && this.skeleton) {
  29478. data = BABYLON.Tools.Slice(data);
  29479. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29480. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29481. if (matricesWeightsData && matricesIndicesData) {
  29482. var needExtras = this.numBoneInfluencers > 4;
  29483. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29484. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29485. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  29486. var tempVector = BABYLON.Tmp.Vector3[0];
  29487. var finalMatrix = BABYLON.Tmp.Matrix[0];
  29488. var tempMatrix = BABYLON.Tmp.Matrix[1];
  29489. var matWeightIdx = 0;
  29490. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  29491. finalMatrix.reset();
  29492. var inf;
  29493. var weight;
  29494. for (inf = 0; inf < 4; inf++) {
  29495. weight = matricesWeightsData[matWeightIdx + inf];
  29496. if (weight <= 0)
  29497. break;
  29498. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  29499. finalMatrix.addToSelf(tempMatrix);
  29500. }
  29501. if (needExtras) {
  29502. for (inf = 0; inf < 4; inf++) {
  29503. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29504. if (weight <= 0)
  29505. break;
  29506. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  29507. finalMatrix.addToSelf(tempMatrix);
  29508. }
  29509. }
  29510. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  29511. tempVector.toArray(data, index);
  29512. }
  29513. }
  29514. }
  29515. return data;
  29516. };
  29517. Mesh.prototype._createGlobalSubMesh = function (force) {
  29518. var totalVertices = this.getTotalVertices();
  29519. if (!totalVertices || !this.getIndices()) {
  29520. return null;
  29521. }
  29522. // Check if we need to recreate the submeshes
  29523. if (this.subMeshes && this.subMeshes.length > 0) {
  29524. var ib = this.getIndices();
  29525. if (!ib) {
  29526. return null;
  29527. }
  29528. var totalIndices = ib.length;
  29529. var needToRecreate = false;
  29530. if (force) {
  29531. needToRecreate = true;
  29532. }
  29533. else {
  29534. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  29535. var submesh = _a[_i];
  29536. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  29537. needToRecreate = true;
  29538. break;
  29539. }
  29540. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  29541. needToRecreate = true;
  29542. break;
  29543. }
  29544. }
  29545. }
  29546. if (!needToRecreate) {
  29547. return this.subMeshes[0];
  29548. }
  29549. }
  29550. this.releaseSubMeshes();
  29551. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  29552. };
  29553. Mesh.prototype.subdivide = function (count) {
  29554. if (count < 1) {
  29555. return;
  29556. }
  29557. var totalIndices = this.getTotalIndices();
  29558. var subdivisionSize = (totalIndices / count) | 0;
  29559. var offset = 0;
  29560. // Ensure that subdivisionSize is a multiple of 3
  29561. while (subdivisionSize % 3 !== 0) {
  29562. subdivisionSize++;
  29563. }
  29564. this.releaseSubMeshes();
  29565. for (var index = 0; index < count; index++) {
  29566. if (offset >= totalIndices) {
  29567. break;
  29568. }
  29569. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  29570. offset += subdivisionSize;
  29571. }
  29572. this.synchronizeInstances();
  29573. };
  29574. /**
  29575. * Sets the vertex data of the mesh geometry for the requested `kind`.
  29576. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  29577. * The `data` are either a numeric array either a Float32Array.
  29578. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  29579. * 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).
  29580. * Note that a new underlying VertexBuffer object is created each call.
  29581. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  29582. *
  29583. * Possible `kind` values :
  29584. * - BABYLON.VertexBuffer.PositionKind
  29585. * - BABYLON.VertexBuffer.UVKind
  29586. * - BABYLON.VertexBuffer.UV2Kind
  29587. * - BABYLON.VertexBuffer.UV3Kind
  29588. * - BABYLON.VertexBuffer.UV4Kind
  29589. * - BABYLON.VertexBuffer.UV5Kind
  29590. * - BABYLON.VertexBuffer.UV6Kind
  29591. * - BABYLON.VertexBuffer.ColorKind
  29592. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29593. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29594. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29595. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29596. *
  29597. * Returns the Mesh.
  29598. */
  29599. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29600. if (updatable === void 0) { updatable = false; }
  29601. if (!this._geometry) {
  29602. var vertexData = new BABYLON.VertexData();
  29603. vertexData.set(data, kind);
  29604. var scene = this.getScene();
  29605. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  29606. }
  29607. else {
  29608. this._geometry.setVerticesData(kind, data, updatable, stride);
  29609. }
  29610. return this;
  29611. };
  29612. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  29613. if (updatable === void 0) { updatable = true; }
  29614. var vb = this.getVertexBuffer(kind);
  29615. if (!vb || vb.isUpdatable() === updatable) {
  29616. return;
  29617. }
  29618. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  29619. };
  29620. /**
  29621. * Sets the mesh VertexBuffer.
  29622. * Returns the Mesh.
  29623. */
  29624. Mesh.prototype.setVerticesBuffer = function (buffer) {
  29625. if (!this._geometry) {
  29626. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  29627. }
  29628. this._geometry.setVerticesBuffer(buffer);
  29629. return this;
  29630. };
  29631. /**
  29632. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  29633. * If the mesh has no geometry, it is simply returned as it is.
  29634. * The `data` are either a numeric array either a Float32Array.
  29635. * No new underlying VertexBuffer object is created.
  29636. * 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.
  29637. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  29638. *
  29639. * Possible `kind` values :
  29640. * - BABYLON.VertexBuffer.PositionKind
  29641. * - BABYLON.VertexBuffer.UVKind
  29642. * - BABYLON.VertexBuffer.UV2Kind
  29643. * - BABYLON.VertexBuffer.UV3Kind
  29644. * - BABYLON.VertexBuffer.UV4Kind
  29645. * - BABYLON.VertexBuffer.UV5Kind
  29646. * - BABYLON.VertexBuffer.UV6Kind
  29647. * - BABYLON.VertexBuffer.ColorKind
  29648. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29649. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29650. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29651. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29652. *
  29653. * Returns the Mesh.
  29654. */
  29655. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  29656. if (!this._geometry) {
  29657. return this;
  29658. }
  29659. if (!makeItUnique) {
  29660. this._geometry.updateVerticesData(kind, data, updateExtends);
  29661. }
  29662. else {
  29663. this.makeGeometryUnique();
  29664. this.updateVerticesData(kind, data, updateExtends, false);
  29665. }
  29666. return this;
  29667. };
  29668. /**
  29669. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  29670. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  29671. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  29672. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  29673. * Returns the Mesh.
  29674. */
  29675. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  29676. if (computeNormals === void 0) { computeNormals = true; }
  29677. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29678. if (!positions) {
  29679. return this;
  29680. }
  29681. positionFunction(positions);
  29682. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  29683. if (computeNormals) {
  29684. var indices = this.getIndices();
  29685. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29686. if (!normals) {
  29687. return this;
  29688. }
  29689. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  29690. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  29691. }
  29692. return this;
  29693. };
  29694. /**
  29695. * Creates a un-shared specific occurence of the geometry for the mesh.
  29696. * Returns the Mesh.
  29697. */
  29698. Mesh.prototype.makeGeometryUnique = function () {
  29699. if (!this._geometry) {
  29700. return this;
  29701. }
  29702. var oldGeometry = this._geometry;
  29703. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  29704. oldGeometry.releaseForMesh(this, true);
  29705. geometry.applyToMesh(this);
  29706. return this;
  29707. };
  29708. /**
  29709. * Sets the mesh indices.
  29710. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  29711. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  29712. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  29713. * This method creates a new index buffer each call.
  29714. * Returns the Mesh.
  29715. */
  29716. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  29717. if (totalVertices === void 0) { totalVertices = null; }
  29718. if (updatable === void 0) { updatable = false; }
  29719. if (!this._geometry) {
  29720. var vertexData = new BABYLON.VertexData();
  29721. vertexData.indices = indices;
  29722. var scene = this.getScene();
  29723. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  29724. }
  29725. else {
  29726. this._geometry.setIndices(indices, totalVertices, updatable);
  29727. }
  29728. return this;
  29729. };
  29730. /**
  29731. * Update the current index buffer
  29732. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  29733. * Returns the Mesh.
  29734. */
  29735. Mesh.prototype.updateIndices = function (indices, offset) {
  29736. if (!this._geometry) {
  29737. return this;
  29738. }
  29739. this._geometry.updateIndices(indices, offset);
  29740. return this;
  29741. };
  29742. /**
  29743. * Invert the geometry to move from a right handed system to a left handed one.
  29744. * Returns the Mesh.
  29745. */
  29746. Mesh.prototype.toLeftHanded = function () {
  29747. if (!this._geometry) {
  29748. return this;
  29749. }
  29750. this._geometry.toLeftHanded();
  29751. return this;
  29752. };
  29753. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  29754. if (!this._geometry) {
  29755. return this;
  29756. }
  29757. var engine = this.getScene().getEngine();
  29758. // Wireframe
  29759. var indexToBind;
  29760. if (this._unIndexed) {
  29761. indexToBind = null;
  29762. }
  29763. else {
  29764. switch (fillMode) {
  29765. case BABYLON.Material.PointFillMode:
  29766. indexToBind = null;
  29767. break;
  29768. case BABYLON.Material.WireFrameFillMode:
  29769. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  29770. break;
  29771. default:
  29772. case BABYLON.Material.TriangleFillMode:
  29773. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  29774. break;
  29775. }
  29776. }
  29777. // VBOs
  29778. this._geometry._bind(effect, indexToBind);
  29779. return this;
  29780. };
  29781. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  29782. if (alternate === void 0) { alternate = false; }
  29783. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  29784. return this;
  29785. }
  29786. this.onBeforeDrawObservable.notifyObservers(this);
  29787. var scene = this.getScene();
  29788. var engine = scene.getEngine();
  29789. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  29790. // or triangles as points
  29791. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  29792. }
  29793. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  29794. // Triangles as wireframe
  29795. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  29796. }
  29797. else {
  29798. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  29799. }
  29800. if (scene._isAlternateRenderingEnabled && !alternate) {
  29801. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  29802. if (!effect || !scene.activeCamera) {
  29803. return this;
  29804. }
  29805. scene._switchToAlternateCameraConfiguration(true);
  29806. this._effectiveMaterial.bindView(effect);
  29807. this._effectiveMaterial.bindViewProjection(effect);
  29808. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  29809. this._draw(subMesh, fillMode, instancesCount, true);
  29810. engine.setViewport(scene.activeCamera.viewport);
  29811. scene._switchToAlternateCameraConfiguration(false);
  29812. this._effectiveMaterial.bindView(effect);
  29813. this._effectiveMaterial.bindViewProjection(effect);
  29814. }
  29815. return this;
  29816. };
  29817. /**
  29818. * Registers for this mesh a javascript function called just before the rendering process.
  29819. * This function is passed the current mesh.
  29820. * Return the Mesh.
  29821. */
  29822. Mesh.prototype.registerBeforeRender = function (func) {
  29823. this.onBeforeRenderObservable.add(func);
  29824. return this;
  29825. };
  29826. /**
  29827. * Disposes a previously registered javascript function called before the rendering.
  29828. * This function is passed the current mesh.
  29829. * Returns the Mesh.
  29830. */
  29831. Mesh.prototype.unregisterBeforeRender = function (func) {
  29832. this.onBeforeRenderObservable.removeCallback(func);
  29833. return this;
  29834. };
  29835. /**
  29836. * Registers for this mesh a javascript function called just after the rendering is complete.
  29837. * This function is passed the current mesh.
  29838. * Returns the Mesh.
  29839. */
  29840. Mesh.prototype.registerAfterRender = function (func) {
  29841. this.onAfterRenderObservable.add(func);
  29842. return this;
  29843. };
  29844. /**
  29845. * Disposes a previously registered javascript function called after the rendering.
  29846. * This function is passed the current mesh.
  29847. * Return the Mesh.
  29848. */
  29849. Mesh.prototype.unregisterAfterRender = function (func) {
  29850. this.onAfterRenderObservable.removeCallback(func);
  29851. return this;
  29852. };
  29853. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  29854. var scene = this.getScene();
  29855. this._batchCache.mustReturn = false;
  29856. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  29857. this._batchCache.visibleInstances[subMeshId] = null;
  29858. if (this._visibleInstances) {
  29859. var currentRenderId = scene.getRenderId();
  29860. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  29861. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  29862. var selfRenderId = this._renderId;
  29863. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  29864. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  29865. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  29866. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  29867. }
  29868. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  29869. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  29870. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  29871. this._batchCache.mustReturn = true;
  29872. return this._batchCache;
  29873. }
  29874. if (currentRenderId !== selfRenderId) {
  29875. this._batchCache.renderSelf[subMeshId] = false;
  29876. }
  29877. }
  29878. this._renderIdForInstances[subMeshId] = currentRenderId;
  29879. }
  29880. return this._batchCache;
  29881. };
  29882. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  29883. var visibleInstances = batch.visibleInstances[subMesh._id];
  29884. if (!visibleInstances) {
  29885. return this;
  29886. }
  29887. var matricesCount = visibleInstances.length + 1;
  29888. var bufferSize = matricesCount * 16 * 4;
  29889. var currentInstancesBufferSize = this._instancesBufferSize;
  29890. var instancesBuffer = this._instancesBuffer;
  29891. while (this._instancesBufferSize < bufferSize) {
  29892. this._instancesBufferSize *= 2;
  29893. }
  29894. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  29895. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  29896. }
  29897. var offset = 0;
  29898. var instancesCount = 0;
  29899. var world = this.getWorldMatrix();
  29900. if (batch.renderSelf[subMesh._id]) {
  29901. world.copyToArray(this._instancesData, offset);
  29902. offset += 16;
  29903. instancesCount++;
  29904. }
  29905. if (visibleInstances) {
  29906. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  29907. var instance = visibleInstances[instanceIndex];
  29908. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  29909. offset += 16;
  29910. instancesCount++;
  29911. }
  29912. }
  29913. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  29914. if (instancesBuffer) {
  29915. instancesBuffer.dispose();
  29916. }
  29917. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  29918. this._instancesBuffer = instancesBuffer;
  29919. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  29920. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  29921. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  29922. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  29923. }
  29924. else {
  29925. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  29926. }
  29927. this._bind(subMesh, effect, fillMode);
  29928. this._draw(subMesh, fillMode, instancesCount);
  29929. engine.unbindInstanceAttributes();
  29930. return this;
  29931. };
  29932. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  29933. var scene = this.getScene();
  29934. var engine = scene.getEngine();
  29935. if (hardwareInstancedRendering) {
  29936. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  29937. }
  29938. else {
  29939. if (batch.renderSelf[subMesh._id]) {
  29940. // Draw
  29941. if (onBeforeDraw) {
  29942. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  29943. }
  29944. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  29945. }
  29946. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  29947. if (visibleInstancesForSubMesh) {
  29948. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  29949. var instance = visibleInstancesForSubMesh[instanceIndex];
  29950. // World
  29951. var world = instance.getWorldMatrix();
  29952. if (onBeforeDraw) {
  29953. onBeforeDraw(true, world, effectiveMaterial);
  29954. }
  29955. // Draw
  29956. this._draw(subMesh, fillMode);
  29957. }
  29958. }
  29959. }
  29960. return this;
  29961. };
  29962. /**
  29963. * Triggers the draw call for the mesh.
  29964. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  29965. * Returns the Mesh.
  29966. */
  29967. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  29968. this.checkOcclusionQuery();
  29969. if (this._isOccluded) {
  29970. return this;
  29971. }
  29972. var scene = this.getScene();
  29973. // Managing instances
  29974. var batch = this._getInstancesRenderList(subMesh._id);
  29975. if (batch.mustReturn) {
  29976. return this;
  29977. }
  29978. // Checking geometry state
  29979. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  29980. return this;
  29981. }
  29982. this.onBeforeRenderObservable.notifyObservers(this);
  29983. var engine = scene.getEngine();
  29984. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29985. // Material
  29986. var material = subMesh.getMaterial();
  29987. if (!material) {
  29988. return this;
  29989. }
  29990. this._effectiveMaterial = material;
  29991. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29992. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29993. return this;
  29994. }
  29995. }
  29996. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29997. return this;
  29998. }
  29999. // Alpha mode
  30000. if (enableAlphaMode) {
  30001. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  30002. }
  30003. // Outline - step 1
  30004. var savedDepthWrite = engine.getDepthWrite();
  30005. if (this.renderOutline) {
  30006. engine.setDepthWrite(false);
  30007. scene.getOutlineRenderer().render(subMesh, batch);
  30008. engine.setDepthWrite(savedDepthWrite);
  30009. }
  30010. var effect;
  30011. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  30012. effect = subMesh.effect;
  30013. }
  30014. else {
  30015. effect = this._effectiveMaterial.getEffect();
  30016. }
  30017. if (!effect) {
  30018. return this;
  30019. }
  30020. var sideOrientation = this.overrideMaterialSideOrientation;
  30021. if (sideOrientation == null) {
  30022. sideOrientation = this._effectiveMaterial.sideOrientation;
  30023. if (this._getWorldMatrixDeterminant() < 0) {
  30024. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  30025. }
  30026. }
  30027. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  30028. if (this._effectiveMaterial.forceDepthWrite) {
  30029. engine.setDepthWrite(true);
  30030. }
  30031. // Bind
  30032. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  30033. if (!hardwareInstancedRendering) {
  30034. this._bind(subMesh, effect, fillMode);
  30035. }
  30036. var world = this.getWorldMatrix();
  30037. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  30038. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  30039. }
  30040. else {
  30041. this._effectiveMaterial.bind(world, this);
  30042. }
  30043. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  30044. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  30045. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  30046. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  30047. }
  30048. // Draw
  30049. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  30050. // Unbind
  30051. this._effectiveMaterial.unbind();
  30052. // Outline - step 2
  30053. if (this.renderOutline && savedDepthWrite) {
  30054. engine.setDepthWrite(true);
  30055. engine.setColorWrite(false);
  30056. scene.getOutlineRenderer().render(subMesh, batch);
  30057. engine.setColorWrite(true);
  30058. }
  30059. // Overlay
  30060. if (this.renderOverlay) {
  30061. var currentMode = engine.getAlphaMode();
  30062. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  30063. scene.getOutlineRenderer().render(subMesh, batch, true);
  30064. engine.setAlphaMode(currentMode);
  30065. }
  30066. this.onAfterRenderObservable.notifyObservers(this);
  30067. return this;
  30068. };
  30069. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  30070. if (isInstance && effectiveMaterial) {
  30071. effectiveMaterial.bindOnlyWorldMatrix(world);
  30072. }
  30073. };
  30074. /**
  30075. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  30076. */
  30077. Mesh.prototype.getEmittedParticleSystems = function () {
  30078. var results = new Array();
  30079. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  30080. var particleSystem = this.getScene().particleSystems[index];
  30081. if (particleSystem.emitter === this) {
  30082. results.push(particleSystem);
  30083. }
  30084. }
  30085. return results;
  30086. };
  30087. /**
  30088. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  30089. */
  30090. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  30091. var results = new Array();
  30092. var descendants = this.getDescendants();
  30093. descendants.push(this);
  30094. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  30095. var particleSystem = this.getScene().particleSystems[index];
  30096. var emitter = particleSystem.emitter;
  30097. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  30098. results.push(particleSystem);
  30099. }
  30100. }
  30101. return results;
  30102. };
  30103. Mesh.prototype._checkDelayState = function () {
  30104. var scene = this.getScene();
  30105. if (this._geometry) {
  30106. this._geometry.load(scene);
  30107. }
  30108. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30109. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30110. this._queueLoad(scene);
  30111. }
  30112. return this;
  30113. };
  30114. Mesh.prototype._queueLoad = function (scene) {
  30115. var _this = this;
  30116. scene._addPendingData(this);
  30117. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  30118. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30119. if (data instanceof ArrayBuffer) {
  30120. _this._delayLoadingFunction(data, _this);
  30121. }
  30122. else {
  30123. _this._delayLoadingFunction(JSON.parse(data), _this);
  30124. }
  30125. _this.instances.forEach(function (instance) {
  30126. instance._syncSubMeshes();
  30127. });
  30128. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30129. scene._removePendingData(_this);
  30130. }, function () { }, scene.database, getBinaryData);
  30131. return this;
  30132. };
  30133. /**
  30134. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  30135. */
  30136. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  30137. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30138. return false;
  30139. }
  30140. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  30141. return false;
  30142. }
  30143. this._checkDelayState();
  30144. return true;
  30145. };
  30146. /**
  30147. * Sets the mesh material by the material or multiMaterial `id` property.
  30148. * The material `id` is a string identifying the material or the multiMaterial.
  30149. * This method returns the Mesh.
  30150. */
  30151. Mesh.prototype.setMaterialByID = function (id) {
  30152. var materials = this.getScene().materials;
  30153. var index;
  30154. for (index = materials.length - 1; index > -1; index--) {
  30155. if (materials[index].id === id) {
  30156. this.material = materials[index];
  30157. return this;
  30158. }
  30159. }
  30160. // Multi
  30161. var multiMaterials = this.getScene().multiMaterials;
  30162. for (index = multiMaterials.length - 1; index > -1; index--) {
  30163. if (multiMaterials[index].id === id) {
  30164. this.material = multiMaterials[index];
  30165. return this;
  30166. }
  30167. }
  30168. return this;
  30169. };
  30170. /**
  30171. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  30172. */
  30173. Mesh.prototype.getAnimatables = function () {
  30174. var results = new Array();
  30175. if (this.material) {
  30176. results.push(this.material);
  30177. }
  30178. if (this.skeleton) {
  30179. results.push(this.skeleton);
  30180. }
  30181. return results;
  30182. };
  30183. /**
  30184. * Modifies the mesh geometry according to the passed transformation matrix.
  30185. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  30186. * The mesh normals are modified accordingly the same transformation.
  30187. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  30188. * Note that, under the hood, this method sets a new VertexBuffer each call.
  30189. * Returns the Mesh.
  30190. */
  30191. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  30192. // Position
  30193. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30194. return this;
  30195. }
  30196. var submeshes = this.subMeshes.splice(0);
  30197. this._resetPointsArrayCache();
  30198. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30199. var temp = new Array();
  30200. var index;
  30201. for (index = 0; index < data.length; index += 3) {
  30202. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  30203. }
  30204. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  30205. // Normals
  30206. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30207. return this;
  30208. }
  30209. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30210. temp = [];
  30211. for (index = 0; index < data.length; index += 3) {
  30212. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  30213. }
  30214. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  30215. // flip faces?
  30216. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  30217. this.flipFaces();
  30218. }
  30219. // Restore submeshes
  30220. this.releaseSubMeshes();
  30221. this.subMeshes = submeshes;
  30222. return this;
  30223. };
  30224. /**
  30225. * Modifies the mesh geometry according to its own current World Matrix.
  30226. * The mesh World Matrix is then reset.
  30227. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  30228. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  30229. * Note that, under the hood, this method sets a new VertexBuffer each call.
  30230. * Returns the Mesh.
  30231. */
  30232. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  30233. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  30234. this.scaling.copyFromFloats(1, 1, 1);
  30235. this.position.copyFromFloats(0, 0, 0);
  30236. this.rotation.copyFromFloats(0, 0, 0);
  30237. //only if quaternion is already set
  30238. if (this.rotationQuaternion) {
  30239. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  30240. }
  30241. this._worldMatrix = BABYLON.Matrix.Identity();
  30242. return this;
  30243. };
  30244. Object.defineProperty(Mesh.prototype, "_positions", {
  30245. // Cache
  30246. get: function () {
  30247. if (this._geometry) {
  30248. return this._geometry._positions;
  30249. }
  30250. return null;
  30251. },
  30252. enumerable: true,
  30253. configurable: true
  30254. });
  30255. Mesh.prototype._resetPointsArrayCache = function () {
  30256. if (this._geometry) {
  30257. this._geometry._resetPointsArrayCache();
  30258. }
  30259. return this;
  30260. };
  30261. Mesh.prototype._generatePointsArray = function () {
  30262. if (this._geometry) {
  30263. return this._geometry._generatePointsArray();
  30264. }
  30265. return false;
  30266. };
  30267. /**
  30268. * Returns a new Mesh object generated from the current mesh properties.
  30269. * This method must not get confused with createInstance().
  30270. * The parameter `name` is a string, the name given to the new mesh.
  30271. * The optional parameter `newParent` can be any Node object (default `null`).
  30272. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  30273. * 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.
  30274. */
  30275. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  30276. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30277. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  30278. };
  30279. /**
  30280. * Releases resources associated with this mesh.
  30281. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  30282. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  30283. */
  30284. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  30285. var _this = this;
  30286. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  30287. this.morphTargetManager = null;
  30288. if (this._geometry) {
  30289. this._geometry.releaseForMesh(this, true);
  30290. }
  30291. // Sources
  30292. var meshes = this.getScene().meshes;
  30293. meshes.forEach(function (abstractMesh) {
  30294. var mesh = abstractMesh;
  30295. if (mesh._source && mesh._source === _this) {
  30296. mesh._source = null;
  30297. }
  30298. });
  30299. this._source = null;
  30300. // Instances
  30301. if (this._instancesBuffer) {
  30302. this._instancesBuffer.dispose();
  30303. this._instancesBuffer = null;
  30304. }
  30305. while (this.instances.length) {
  30306. this.instances[0].dispose();
  30307. }
  30308. // Effect layers.
  30309. var effectLayers = this.getScene().effectLayers;
  30310. for (var i = 0; i < effectLayers.length; i++) {
  30311. var effectLayer = effectLayers[i];
  30312. if (effectLayer) {
  30313. effectLayer._disposeMesh(this);
  30314. }
  30315. }
  30316. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  30317. };
  30318. /**
  30319. * Modifies the mesh geometry according to a displacement map.
  30320. * 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.
  30321. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  30322. * This method returns nothing.
  30323. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  30324. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  30325. * 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.
  30326. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  30327. * The parameter `uvScale` is an optional vector2 used to scale UV.
  30328. *
  30329. * Returns the Mesh.
  30330. */
  30331. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  30332. var _this = this;
  30333. var scene = this.getScene();
  30334. var onload = function (img) {
  30335. // Getting height map data
  30336. var canvas = document.createElement("canvas");
  30337. var context = canvas.getContext("2d");
  30338. var heightMapWidth = img.width;
  30339. var heightMapHeight = img.height;
  30340. canvas.width = heightMapWidth;
  30341. canvas.height = heightMapHeight;
  30342. context.drawImage(img, 0, 0);
  30343. // Create VertexData from map data
  30344. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  30345. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  30346. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  30347. //execute success callback, if set
  30348. if (onSuccess) {
  30349. onSuccess(_this);
  30350. }
  30351. };
  30352. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  30353. return this;
  30354. };
  30355. /**
  30356. * Modifies the mesh geometry according to a displacementMap buffer.
  30357. * 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.
  30358. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  30359. * This method returns nothing.
  30360. * 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.
  30361. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  30362. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  30363. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  30364. * The parameter `uvScale` is an optional vector2 used to scale UV.
  30365. *
  30366. * Returns the Mesh.
  30367. */
  30368. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  30369. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  30370. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  30371. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30372. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  30373. return this;
  30374. }
  30375. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30376. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30377. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30378. var position = BABYLON.Vector3.Zero();
  30379. var normal = BABYLON.Vector3.Zero();
  30380. var uv = BABYLON.Vector2.Zero();
  30381. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  30382. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  30383. for (var index = 0; index < positions.length; index += 3) {
  30384. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  30385. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  30386. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  30387. // Compute height
  30388. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  30389. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  30390. var pos = (u + v * heightMapWidth) * 4;
  30391. var r = buffer[pos] / 255.0;
  30392. var g = buffer[pos + 1] / 255.0;
  30393. var b = buffer[pos + 2] / 255.0;
  30394. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  30395. normal.normalize();
  30396. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  30397. position = position.add(normal);
  30398. position.toArray(positions, index);
  30399. }
  30400. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  30401. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  30402. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30403. return this;
  30404. };
  30405. /**
  30406. * Modify the mesh to get a flat shading rendering.
  30407. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  30408. * This method returns the Mesh.
  30409. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  30410. */
  30411. Mesh.prototype.convertToFlatShadedMesh = function () {
  30412. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  30413. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  30414. var kinds = this.getVerticesDataKinds();
  30415. var vbs = {};
  30416. var data = {};
  30417. var newdata = {};
  30418. var updatableNormals = false;
  30419. var kindIndex;
  30420. var kind;
  30421. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30422. kind = kinds[kindIndex];
  30423. var vertexBuffer = this.getVertexBuffer(kind);
  30424. if (kind === BABYLON.VertexBuffer.NormalKind) {
  30425. updatableNormals = vertexBuffer.isUpdatable();
  30426. kinds.splice(kindIndex, 1);
  30427. kindIndex--;
  30428. continue;
  30429. }
  30430. vbs[kind] = vertexBuffer;
  30431. data[kind] = vbs[kind].getData();
  30432. newdata[kind] = [];
  30433. }
  30434. // Save previous submeshes
  30435. var previousSubmeshes = this.subMeshes.slice(0);
  30436. var indices = this.getIndices();
  30437. var totalIndices = this.getTotalIndices();
  30438. // Generating unique vertices per face
  30439. var index;
  30440. for (index = 0; index < totalIndices; index++) {
  30441. var vertexIndex = indices[index];
  30442. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30443. kind = kinds[kindIndex];
  30444. var stride = vbs[kind].getStrideSize();
  30445. for (var offset = 0; offset < stride; offset++) {
  30446. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  30447. }
  30448. }
  30449. }
  30450. // Updating faces & normal
  30451. var normals = [];
  30452. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  30453. for (index = 0; index < totalIndices; index += 3) {
  30454. indices[index] = index;
  30455. indices[index + 1] = index + 1;
  30456. indices[index + 2] = index + 2;
  30457. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  30458. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  30459. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  30460. var p1p2 = p1.subtract(p2);
  30461. var p3p2 = p3.subtract(p2);
  30462. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  30463. // Store same normals for every vertex
  30464. for (var localIndex = 0; localIndex < 3; localIndex++) {
  30465. normals.push(normal.x);
  30466. normals.push(normal.y);
  30467. normals.push(normal.z);
  30468. }
  30469. }
  30470. this.setIndices(indices);
  30471. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  30472. // Updating vertex buffers
  30473. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30474. kind = kinds[kindIndex];
  30475. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  30476. }
  30477. // Updating submeshes
  30478. this.releaseSubMeshes();
  30479. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  30480. var previousOne = previousSubmeshes[submeshIndex];
  30481. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  30482. }
  30483. this.synchronizeInstances();
  30484. return this;
  30485. };
  30486. /**
  30487. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  30488. * In other words, more vertices, no more indices and a single bigger VBO.
  30489. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  30490. * Returns the Mesh.
  30491. */
  30492. Mesh.prototype.convertToUnIndexedMesh = function () {
  30493. /// <summary>Remove indices by unfolding faces into buffers</summary>
  30494. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  30495. var kinds = this.getVerticesDataKinds();
  30496. var vbs = {};
  30497. var data = {};
  30498. var newdata = {};
  30499. var kindIndex;
  30500. var kind;
  30501. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30502. kind = kinds[kindIndex];
  30503. var vertexBuffer = this.getVertexBuffer(kind);
  30504. vbs[kind] = vertexBuffer;
  30505. data[kind] = vbs[kind].getData();
  30506. newdata[kind] = [];
  30507. }
  30508. // Save previous submeshes
  30509. var previousSubmeshes = this.subMeshes.slice(0);
  30510. var indices = this.getIndices();
  30511. var totalIndices = this.getTotalIndices();
  30512. // Generating unique vertices per face
  30513. var index;
  30514. for (index = 0; index < totalIndices; index++) {
  30515. var vertexIndex = indices[index];
  30516. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30517. kind = kinds[kindIndex];
  30518. var stride = vbs[kind].getStrideSize();
  30519. for (var offset = 0; offset < stride; offset++) {
  30520. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  30521. }
  30522. }
  30523. }
  30524. // Updating indices
  30525. for (index = 0; index < totalIndices; index += 3) {
  30526. indices[index] = index;
  30527. indices[index + 1] = index + 1;
  30528. indices[index + 2] = index + 2;
  30529. }
  30530. this.setIndices(indices);
  30531. // Updating vertex buffers
  30532. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30533. kind = kinds[kindIndex];
  30534. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  30535. }
  30536. // Updating submeshes
  30537. this.releaseSubMeshes();
  30538. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  30539. var previousOne = previousSubmeshes[submeshIndex];
  30540. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  30541. }
  30542. this._unIndexed = true;
  30543. this.synchronizeInstances();
  30544. return this;
  30545. };
  30546. /**
  30547. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  30548. * This method returns the Mesh.
  30549. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  30550. */
  30551. Mesh.prototype.flipFaces = function (flipNormals) {
  30552. if (flipNormals === void 0) { flipNormals = false; }
  30553. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  30554. var i;
  30555. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  30556. for (i = 0; i < vertex_data.normals.length; i++) {
  30557. vertex_data.normals[i] *= -1;
  30558. }
  30559. }
  30560. if (vertex_data.indices) {
  30561. var temp;
  30562. for (i = 0; i < vertex_data.indices.length; i += 3) {
  30563. // reassign indices
  30564. temp = vertex_data.indices[i + 1];
  30565. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  30566. vertex_data.indices[i + 2] = temp;
  30567. }
  30568. }
  30569. vertex_data.applyToMesh(this);
  30570. return this;
  30571. };
  30572. // Instances
  30573. /**
  30574. * Creates a new InstancedMesh object from the mesh model.
  30575. * An instance shares the same properties and the same material than its model.
  30576. * Only these properties of each instance can then be set individually :
  30577. * - position
  30578. * - rotation
  30579. * - rotationQuaternion
  30580. * - setPivotMatrix
  30581. * - scaling
  30582. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  30583. * Warning : this method is not supported for Line mesh and LineSystem
  30584. */
  30585. Mesh.prototype.createInstance = function (name) {
  30586. return new BABYLON.InstancedMesh(name, this);
  30587. };
  30588. /**
  30589. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  30590. * After this call, all the mesh instances have the same submeshes than the current mesh.
  30591. * This method returns the Mesh.
  30592. */
  30593. Mesh.prototype.synchronizeInstances = function () {
  30594. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  30595. var instance = this.instances[instanceIndex];
  30596. instance._syncSubMeshes();
  30597. }
  30598. return this;
  30599. };
  30600. /**
  30601. * Simplify the mesh according to the given array of settings.
  30602. * Function will return immediately and will simplify async. It returns the Mesh.
  30603. * @param settings a collection of simplification settings.
  30604. * @param parallelProcessing should all levels calculate parallel or one after the other.
  30605. * @param type the type of simplification to run.
  30606. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  30607. */
  30608. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  30609. if (parallelProcessing === void 0) { parallelProcessing = true; }
  30610. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  30611. this.getScene().simplificationQueue.addTask({
  30612. settings: settings,
  30613. parallelProcessing: parallelProcessing,
  30614. mesh: this,
  30615. simplificationType: simplificationType,
  30616. successCallback: successCallback
  30617. });
  30618. return this;
  30619. };
  30620. /**
  30621. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  30622. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  30623. * This should be used together with the simplification to avoid disappearing triangles.
  30624. * Returns the Mesh.
  30625. * @param successCallback an optional success callback to be called after the optimization finished.
  30626. */
  30627. Mesh.prototype.optimizeIndices = function (successCallback) {
  30628. var _this = this;
  30629. var indices = this.getIndices();
  30630. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30631. if (!positions || !indices) {
  30632. return this;
  30633. }
  30634. var vectorPositions = new Array();
  30635. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  30636. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  30637. }
  30638. var dupes = new Array();
  30639. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  30640. var realPos = vectorPositions.length - 1 - iteration;
  30641. var testedPosition = vectorPositions[realPos];
  30642. for (var j = 0; j < realPos; ++j) {
  30643. var againstPosition = vectorPositions[j];
  30644. if (testedPosition.equals(againstPosition)) {
  30645. dupes[realPos] = j;
  30646. break;
  30647. }
  30648. }
  30649. }, function () {
  30650. for (var i = 0; i < indices.length; ++i) {
  30651. indices[i] = dupes[indices[i]] || indices[i];
  30652. }
  30653. //indices are now reordered
  30654. var originalSubMeshes = _this.subMeshes.slice(0);
  30655. _this.setIndices(indices);
  30656. _this.subMeshes = originalSubMeshes;
  30657. if (successCallback) {
  30658. successCallback(_this);
  30659. }
  30660. });
  30661. return this;
  30662. };
  30663. Mesh.prototype.serialize = function (serializationObject) {
  30664. serializationObject.name = this.name;
  30665. serializationObject.id = this.id;
  30666. serializationObject.type = this.getClassName();
  30667. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30668. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30669. }
  30670. serializationObject.position = this.position.asArray();
  30671. if (this.rotationQuaternion) {
  30672. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  30673. }
  30674. else if (this.rotation) {
  30675. serializationObject.rotation = this.rotation.asArray();
  30676. }
  30677. serializationObject.scaling = this.scaling.asArray();
  30678. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  30679. serializationObject.isEnabled = this.isEnabled(false);
  30680. serializationObject.isVisible = this.isVisible;
  30681. serializationObject.infiniteDistance = this.infiniteDistance;
  30682. serializationObject.pickable = this.isPickable;
  30683. serializationObject.receiveShadows = this.receiveShadows;
  30684. serializationObject.billboardMode = this.billboardMode;
  30685. serializationObject.visibility = this.visibility;
  30686. serializationObject.checkCollisions = this.checkCollisions;
  30687. serializationObject.isBlocker = this.isBlocker;
  30688. // Parent
  30689. if (this.parent) {
  30690. serializationObject.parentId = this.parent.id;
  30691. }
  30692. // Geometry
  30693. serializationObject.isUnIndexed = this.isUnIndexed;
  30694. var geometry = this._geometry;
  30695. if (geometry) {
  30696. var geometryId = geometry.id;
  30697. serializationObject.geometryId = geometryId;
  30698. // SubMeshes
  30699. serializationObject.subMeshes = [];
  30700. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  30701. var subMesh = this.subMeshes[subIndex];
  30702. serializationObject.subMeshes.push({
  30703. materialIndex: subMesh.materialIndex,
  30704. verticesStart: subMesh.verticesStart,
  30705. verticesCount: subMesh.verticesCount,
  30706. indexStart: subMesh.indexStart,
  30707. indexCount: subMesh.indexCount
  30708. });
  30709. }
  30710. }
  30711. // Material
  30712. if (this.material) {
  30713. serializationObject.materialId = this.material.id;
  30714. }
  30715. else {
  30716. this.material = null;
  30717. }
  30718. // Morph targets
  30719. if (this.morphTargetManager) {
  30720. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  30721. }
  30722. // Skeleton
  30723. if (this.skeleton) {
  30724. serializationObject.skeletonId = this.skeleton.id;
  30725. }
  30726. // Physics
  30727. //TODO implement correct serialization for physics impostors.
  30728. var impostor = this.getPhysicsImpostor();
  30729. if (impostor) {
  30730. serializationObject.physicsMass = impostor.getParam("mass");
  30731. serializationObject.physicsFriction = impostor.getParam("friction");
  30732. serializationObject.physicsRestitution = impostor.getParam("mass");
  30733. serializationObject.physicsImpostor = impostor.type;
  30734. }
  30735. // Metadata
  30736. if (this.metadata) {
  30737. serializationObject.metadata = this.metadata;
  30738. }
  30739. // Instances
  30740. serializationObject.instances = [];
  30741. for (var index = 0; index < this.instances.length; index++) {
  30742. var instance = this.instances[index];
  30743. var serializationInstance = {
  30744. name: instance.name,
  30745. id: instance.id,
  30746. position: instance.position.asArray(),
  30747. scaling: instance.scaling.asArray()
  30748. };
  30749. if (instance.rotationQuaternion) {
  30750. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30751. }
  30752. else if (instance.rotation) {
  30753. serializationInstance.rotation = instance.rotation.asArray();
  30754. }
  30755. serializationObject.instances.push(serializationInstance);
  30756. // Animations
  30757. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30758. serializationInstance.ranges = instance.serializeAnimationRanges();
  30759. }
  30760. //
  30761. // Animations
  30762. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30763. serializationObject.ranges = this.serializeAnimationRanges();
  30764. // Layer mask
  30765. serializationObject.layerMask = this.layerMask;
  30766. // Alpha
  30767. serializationObject.alphaIndex = this.alphaIndex;
  30768. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  30769. // Overlay
  30770. serializationObject.overlayAlpha = this.overlayAlpha;
  30771. serializationObject.overlayColor = this.overlayColor.asArray();
  30772. serializationObject.renderOverlay = this.renderOverlay;
  30773. // Fog
  30774. serializationObject.applyFog = this.applyFog;
  30775. // Action Manager
  30776. if (this.actionManager) {
  30777. serializationObject.actions = this.actionManager.serialize(this.name);
  30778. }
  30779. };
  30780. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  30781. if (!this.geometry) {
  30782. return;
  30783. }
  30784. this._markSubMeshesAsAttributesDirty();
  30785. var morphTargetManager = this._morphTargetManager;
  30786. if (morphTargetManager && morphTargetManager.vertexCount) {
  30787. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  30788. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  30789. this.morphTargetManager = null;
  30790. return;
  30791. }
  30792. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  30793. var morphTarget = morphTargetManager.getActiveTarget(index);
  30794. var positions = morphTarget.getPositions();
  30795. if (!positions) {
  30796. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  30797. return;
  30798. }
  30799. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  30800. var normals = morphTarget.getNormals();
  30801. if (normals) {
  30802. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  30803. }
  30804. var tangents = morphTarget.getTangents();
  30805. if (tangents) {
  30806. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  30807. }
  30808. }
  30809. }
  30810. else {
  30811. var index = 0;
  30812. // Positions
  30813. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  30814. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  30815. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  30816. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  30817. }
  30818. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  30819. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  30820. }
  30821. index++;
  30822. }
  30823. }
  30824. };
  30825. // Statics
  30826. /**
  30827. * Returns a new Mesh object parsed from the source provided.
  30828. * The parameter `parsedMesh` is the source.
  30829. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  30830. */
  30831. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  30832. var mesh;
  30833. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  30834. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  30835. }
  30836. else {
  30837. mesh = new Mesh(parsedMesh.name, scene);
  30838. }
  30839. mesh.id = parsedMesh.id;
  30840. if (BABYLON.Tags) {
  30841. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  30842. }
  30843. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  30844. if (parsedMesh.metadata !== undefined) {
  30845. mesh.metadata = parsedMesh.metadata;
  30846. }
  30847. if (parsedMesh.rotationQuaternion) {
  30848. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  30849. }
  30850. else if (parsedMesh.rotation) {
  30851. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  30852. }
  30853. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  30854. if (parsedMesh.localMatrix) {
  30855. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  30856. }
  30857. else if (parsedMesh.pivotMatrix) {
  30858. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  30859. }
  30860. mesh.setEnabled(parsedMesh.isEnabled);
  30861. mesh.isVisible = parsedMesh.isVisible;
  30862. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  30863. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  30864. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  30865. if (parsedMesh.applyFog !== undefined) {
  30866. mesh.applyFog = parsedMesh.applyFog;
  30867. }
  30868. if (parsedMesh.pickable !== undefined) {
  30869. mesh.isPickable = parsedMesh.pickable;
  30870. }
  30871. if (parsedMesh.alphaIndex !== undefined) {
  30872. mesh.alphaIndex = parsedMesh.alphaIndex;
  30873. }
  30874. mesh.receiveShadows = parsedMesh.receiveShadows;
  30875. mesh.billboardMode = parsedMesh.billboardMode;
  30876. if (parsedMesh.visibility !== undefined) {
  30877. mesh.visibility = parsedMesh.visibility;
  30878. }
  30879. mesh.checkCollisions = parsedMesh.checkCollisions;
  30880. if (parsedMesh.isBlocker !== undefined) {
  30881. mesh.isBlocker = parsedMesh.isBlocker;
  30882. }
  30883. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  30884. // freezeWorldMatrix
  30885. if (parsedMesh.freezeWorldMatrix) {
  30886. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  30887. }
  30888. // Parent
  30889. if (parsedMesh.parentId) {
  30890. mesh._waitingParentId = parsedMesh.parentId;
  30891. }
  30892. // Actions
  30893. if (parsedMesh.actions !== undefined) {
  30894. mesh._waitingActions = parsedMesh.actions;
  30895. }
  30896. // Overlay
  30897. if (parsedMesh.overlayAlpha !== undefined) {
  30898. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  30899. }
  30900. if (parsedMesh.overlayColor !== undefined) {
  30901. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  30902. }
  30903. if (parsedMesh.renderOverlay !== undefined) {
  30904. mesh.renderOverlay = parsedMesh.renderOverlay;
  30905. }
  30906. // Geometry
  30907. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  30908. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  30909. if (parsedMesh.delayLoadingFile) {
  30910. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30911. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  30912. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  30913. if (parsedMesh._binaryInfo) {
  30914. mesh._binaryInfo = parsedMesh._binaryInfo;
  30915. }
  30916. mesh._delayInfo = [];
  30917. if (parsedMesh.hasUVs) {
  30918. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30919. }
  30920. if (parsedMesh.hasUVs2) {
  30921. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30922. }
  30923. if (parsedMesh.hasUVs3) {
  30924. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30925. }
  30926. if (parsedMesh.hasUVs4) {
  30927. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30928. }
  30929. if (parsedMesh.hasUVs5) {
  30930. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30931. }
  30932. if (parsedMesh.hasUVs6) {
  30933. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30934. }
  30935. if (parsedMesh.hasColors) {
  30936. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30937. }
  30938. if (parsedMesh.hasMatricesIndices) {
  30939. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30940. }
  30941. if (parsedMesh.hasMatricesWeights) {
  30942. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30943. }
  30944. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  30945. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  30946. mesh._checkDelayState();
  30947. }
  30948. }
  30949. else {
  30950. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  30951. }
  30952. // Material
  30953. if (parsedMesh.materialId) {
  30954. mesh.setMaterialByID(parsedMesh.materialId);
  30955. }
  30956. else {
  30957. mesh.material = null;
  30958. }
  30959. // Morph targets
  30960. if (parsedMesh.morphTargetManagerId > -1) {
  30961. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  30962. }
  30963. // Skeleton
  30964. if (parsedMesh.skeletonId > -1) {
  30965. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  30966. if (parsedMesh.numBoneInfluencers) {
  30967. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  30968. }
  30969. }
  30970. // Animations
  30971. if (parsedMesh.animations) {
  30972. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30973. var parsedAnimation = parsedMesh.animations[animationIndex];
  30974. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30975. }
  30976. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  30977. }
  30978. if (parsedMesh.autoAnimate) {
  30979. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  30980. }
  30981. // Layer Mask
  30982. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  30983. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  30984. }
  30985. else {
  30986. mesh.layerMask = 0x0FFFFFFF;
  30987. }
  30988. // Physics
  30989. if (parsedMesh.physicsImpostor) {
  30990. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30991. mass: parsedMesh.physicsMass,
  30992. friction: parsedMesh.physicsFriction,
  30993. restitution: parsedMesh.physicsRestitution
  30994. }, scene);
  30995. }
  30996. // Instances
  30997. if (parsedMesh.instances) {
  30998. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30999. var parsedInstance = parsedMesh.instances[index];
  31000. var instance = mesh.createInstance(parsedInstance.name);
  31001. if (parsedInstance.id) {
  31002. instance.id = parsedInstance.id;
  31003. }
  31004. if (BABYLON.Tags) {
  31005. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  31006. }
  31007. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  31008. if (parsedInstance.parentId) {
  31009. instance._waitingParentId = parsedInstance.parentId;
  31010. }
  31011. if (parsedInstance.rotationQuaternion) {
  31012. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  31013. }
  31014. else if (parsedInstance.rotation) {
  31015. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  31016. }
  31017. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  31018. instance.checkCollisions = mesh.checkCollisions;
  31019. if (parsedMesh.animations) {
  31020. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  31021. parsedAnimation = parsedMesh.animations[animationIndex];
  31022. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31023. }
  31024. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  31025. }
  31026. }
  31027. }
  31028. return mesh;
  31029. };
  31030. /**
  31031. * Creates a ribbon mesh.
  31032. * Please consider using the same method from the MeshBuilder class instead.
  31033. * 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.
  31034. *
  31035. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  31036. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  31037. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  31038. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  31039. * 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.
  31040. * 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.
  31041. * 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
  31042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31045. */
  31046. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  31047. if (closeArray === void 0) { closeArray = false; }
  31048. if (updatable === void 0) { updatable = false; }
  31049. return BABYLON.MeshBuilder.CreateRibbon(name, {
  31050. pathArray: pathArray,
  31051. closeArray: closeArray,
  31052. closePath: closePath,
  31053. offset: offset,
  31054. updatable: updatable,
  31055. sideOrientation: sideOrientation,
  31056. instance: instance
  31057. }, scene);
  31058. };
  31059. /**
  31060. * Creates a plane polygonal mesh. By default, this is a disc.
  31061. * Please consider using the same method from the MeshBuilder class instead.
  31062. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  31063. * 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.
  31064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31067. */
  31068. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  31069. if (scene === void 0) { scene = null; }
  31070. var options = {
  31071. radius: radius,
  31072. tessellation: tessellation,
  31073. sideOrientation: sideOrientation,
  31074. updatable: updatable
  31075. };
  31076. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  31077. };
  31078. /**
  31079. * Creates a box mesh.
  31080. * Please consider using the same method from the MeshBuilder class instead.
  31081. * The parameter `size` sets the size (float) of each box side (default 1).
  31082. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31083. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31085. */
  31086. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  31087. if (scene === void 0) { scene = null; }
  31088. var options = {
  31089. size: size,
  31090. sideOrientation: sideOrientation,
  31091. updatable: updatable
  31092. };
  31093. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  31094. };
  31095. /**
  31096. * Creates a sphere mesh.
  31097. * Please consider using the same method from the MeshBuilder class instead.
  31098. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  31099. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  31100. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31101. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31103. */
  31104. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  31105. var options = {
  31106. segments: segments,
  31107. diameterX: diameter,
  31108. diameterY: diameter,
  31109. diameterZ: diameter,
  31110. sideOrientation: sideOrientation,
  31111. updatable: updatable
  31112. };
  31113. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  31114. };
  31115. /**
  31116. * Creates a cylinder or a cone mesh.
  31117. * Please consider using the same method from the MeshBuilder class instead.
  31118. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  31119. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  31120. * 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.
  31121. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  31122. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  31123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31126. */
  31127. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  31128. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  31129. if (scene !== undefined) {
  31130. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  31131. updatable = scene;
  31132. }
  31133. scene = subdivisions;
  31134. subdivisions = 1;
  31135. }
  31136. var options = {
  31137. height: height,
  31138. diameterTop: diameterTop,
  31139. diameterBottom: diameterBottom,
  31140. tessellation: tessellation,
  31141. subdivisions: subdivisions,
  31142. sideOrientation: sideOrientation,
  31143. updatable: updatable
  31144. };
  31145. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  31146. };
  31147. // Torus (Code from SharpDX.org)
  31148. /**
  31149. * Creates a torus mesh.
  31150. * Please consider using the same method from the MeshBuilder class instead.
  31151. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  31152. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  31153. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  31154. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31155. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31157. */
  31158. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  31159. var options = {
  31160. diameter: diameter,
  31161. thickness: thickness,
  31162. tessellation: tessellation,
  31163. sideOrientation: sideOrientation,
  31164. updatable: updatable
  31165. };
  31166. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  31167. };
  31168. /**
  31169. * Creates a torus knot mesh.
  31170. * Please consider using the same method from the MeshBuilder class instead.
  31171. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  31172. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  31173. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  31174. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  31175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31176. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31178. */
  31179. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  31180. var options = {
  31181. radius: radius,
  31182. tube: tube,
  31183. radialSegments: radialSegments,
  31184. tubularSegments: tubularSegments,
  31185. p: p,
  31186. q: q,
  31187. sideOrientation: sideOrientation,
  31188. updatable: updatable
  31189. };
  31190. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  31191. };
  31192. /**
  31193. * Creates a line mesh.
  31194. * Please consider using the same method from the MeshBuilder class instead.
  31195. * 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.
  31196. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  31197. * The parameter `points` is an array successive Vector3.
  31198. * 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
  31199. * When updating an instance, remember that only point positions can change, not the number of points.
  31200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31201. */
  31202. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  31203. if (scene === void 0) { scene = null; }
  31204. if (updatable === void 0) { updatable = false; }
  31205. if (instance === void 0) { instance = null; }
  31206. var options = {
  31207. points: points,
  31208. updatable: updatable,
  31209. instance: instance
  31210. };
  31211. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  31212. };
  31213. /**
  31214. * Creates a dashed line mesh.
  31215. * Please consider using the same method from the MeshBuilder class instead.
  31216. * 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.
  31217. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  31218. * The parameter `points` is an array successive Vector3.
  31219. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  31220. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  31221. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  31222. * 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
  31223. * When updating an instance, remember that only point positions can change, not the number of points.
  31224. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31225. */
  31226. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  31227. if (scene === void 0) { scene = null; }
  31228. var options = {
  31229. points: points,
  31230. dashSize: dashSize,
  31231. gapSize: gapSize,
  31232. dashNb: dashNb,
  31233. updatable: updatable,
  31234. instance: instance
  31235. };
  31236. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  31237. };
  31238. /**
  31239. * Creates a polygon mesh.
  31240. * Please consider using the same method from the MeshBuilder class instead.
  31241. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  31242. * 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.
  31243. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31245. * Remember you can only change the shape positions, not their number when updating a polygon.
  31246. */
  31247. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  31248. var options = {
  31249. shape: shape,
  31250. holes: holes,
  31251. updatable: updatable,
  31252. sideOrientation: sideOrientation
  31253. };
  31254. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  31255. };
  31256. /**
  31257. * Creates an extruded polygon mesh, with depth in the Y direction.
  31258. * Please consider using the same method from the MeshBuilder class instead.
  31259. */
  31260. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  31261. var options = {
  31262. shape: shape,
  31263. holes: holes,
  31264. depth: depth,
  31265. updatable: updatable,
  31266. sideOrientation: sideOrientation
  31267. };
  31268. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  31269. };
  31270. /**
  31271. * Creates an extruded shape mesh.
  31272. * 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.
  31273. * Please consider using the same method from the MeshBuilder class instead.
  31274. *
  31275. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  31276. * 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
  31277. * extruded along the Z axis.
  31278. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  31279. * 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.
  31280. * The parameter `scale` (float, default 1) is the value to scale the shape.
  31281. * 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
  31282. * 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
  31283. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  31284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31287. */
  31288. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  31289. if (scene === void 0) { scene = null; }
  31290. var options = {
  31291. shape: shape,
  31292. path: path,
  31293. scale: scale,
  31294. rotation: rotation,
  31295. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  31296. sideOrientation: sideOrientation,
  31297. instance: instance,
  31298. updatable: updatable
  31299. };
  31300. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  31301. };
  31302. /**
  31303. * Creates an custom extruded shape mesh.
  31304. * 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.
  31305. * Please consider using the same method from the MeshBuilder class instead.
  31306. *
  31307. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  31308. * 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
  31309. * extruded along the Z axis.
  31310. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  31311. * 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
  31312. * and the distance of this point from the begining of the path :
  31313. * ```javascript
  31314. * var rotationFunction = function(i, distance) {
  31315. * // do things
  31316. * return rotationValue; }
  31317. * ```
  31318. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  31319. * 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
  31320. * and the distance of this point from the begining of the path :
  31321. * ```javascript
  31322. * var scaleFunction = function(i, distance) {
  31323. * // do things
  31324. * return scaleValue;}
  31325. * ```
  31326. * It must returns a float value that will be the scale value applied to the shape on each path point.
  31327. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  31328. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  31329. * 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
  31330. * 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
  31331. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  31332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31335. */
  31336. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  31337. var options = {
  31338. shape: shape,
  31339. path: path,
  31340. scaleFunction: scaleFunction,
  31341. rotationFunction: rotationFunction,
  31342. ribbonCloseArray: ribbonCloseArray,
  31343. ribbonClosePath: ribbonClosePath,
  31344. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  31345. sideOrientation: sideOrientation,
  31346. instance: instance,
  31347. updatable: updatable
  31348. };
  31349. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  31350. };
  31351. /**
  31352. * Creates lathe mesh.
  31353. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  31354. * Please consider using the same method from the MeshBuilder class instead.
  31355. * 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
  31356. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  31357. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  31358. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  31359. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31360. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31362. */
  31363. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  31364. var options = {
  31365. shape: shape,
  31366. radius: radius,
  31367. tessellation: tessellation,
  31368. sideOrientation: sideOrientation,
  31369. updatable: updatable
  31370. };
  31371. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  31372. };
  31373. /**
  31374. * Creates a plane mesh.
  31375. * Please consider using the same method from the MeshBuilder class instead.
  31376. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  31377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31380. */
  31381. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  31382. var options = {
  31383. size: size,
  31384. width: size,
  31385. height: size,
  31386. sideOrientation: sideOrientation,
  31387. updatable: updatable
  31388. };
  31389. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  31390. };
  31391. /**
  31392. * Creates a ground mesh.
  31393. * Please consider using the same method from the MeshBuilder class instead.
  31394. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  31395. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  31396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31397. */
  31398. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  31399. var options = {
  31400. width: width,
  31401. height: height,
  31402. subdivisions: subdivisions,
  31403. updatable: updatable
  31404. };
  31405. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  31406. };
  31407. /**
  31408. * Creates a tiled ground mesh.
  31409. * Please consider using the same method from the MeshBuilder class instead.
  31410. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  31411. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  31412. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  31413. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  31414. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  31415. * numbers of subdivisions on the ground width and height of each tile.
  31416. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31417. */
  31418. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  31419. var options = {
  31420. xmin: xmin,
  31421. zmin: zmin,
  31422. xmax: xmax,
  31423. zmax: zmax,
  31424. subdivisions: subdivisions,
  31425. precision: precision,
  31426. updatable: updatable
  31427. };
  31428. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  31429. };
  31430. /**
  31431. * Creates a ground mesh from a height map.
  31432. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  31433. * Please consider using the same method from the MeshBuilder class instead.
  31434. * The parameter `url` sets the URL of the height map image resource.
  31435. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  31436. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  31437. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  31438. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  31439. * 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).
  31440. * This function is passed the newly built mesh :
  31441. * ```javascript
  31442. * function(mesh) { // do things
  31443. * return; }
  31444. * ```
  31445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31446. */
  31447. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  31448. var options = {
  31449. width: width,
  31450. height: height,
  31451. subdivisions: subdivisions,
  31452. minHeight: minHeight,
  31453. maxHeight: maxHeight,
  31454. updatable: updatable,
  31455. onReady: onReady
  31456. };
  31457. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  31458. };
  31459. /**
  31460. * Creates a tube mesh.
  31461. * 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.
  31462. * Please consider using the same method from the MeshBuilder class instead.
  31463. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  31464. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  31465. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  31466. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  31467. * 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.
  31468. * It must return a radius value (positive float) :
  31469. * ```javascript
  31470. * var radiusFunction = function(i, distance) {
  31471. * // do things
  31472. * return radius; }
  31473. * ```
  31474. * 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
  31475. * 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
  31476. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31479. */
  31480. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  31481. var options = {
  31482. path: path,
  31483. radius: radius,
  31484. tessellation: tessellation,
  31485. radiusFunction: radiusFunction,
  31486. arc: 1,
  31487. cap: cap,
  31488. updatable: updatable,
  31489. sideOrientation: sideOrientation,
  31490. instance: instance
  31491. };
  31492. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  31493. };
  31494. /**
  31495. * Creates a polyhedron mesh.
  31496. * Please consider using the same method from the MeshBuilder class instead.
  31497. * 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
  31498. * to choose the wanted type.
  31499. * The parameter `size` (positive float, default 1) sets the polygon size.
  31500. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  31501. * 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`.
  31502. * 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
  31503. * 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)`).
  31504. * 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
  31505. * 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.
  31506. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31507. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31508. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31509. */
  31510. Mesh.CreatePolyhedron = function (name, options, scene) {
  31511. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  31512. };
  31513. /**
  31514. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  31515. * Please consider using the same method from the MeshBuilder class instead.
  31516. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  31517. * 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`).
  31518. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  31519. * 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.
  31520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31523. */
  31524. Mesh.CreateIcoSphere = function (name, options, scene) {
  31525. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  31526. };
  31527. /**
  31528. * Creates a decal mesh.
  31529. * Please consider using the same method from the MeshBuilder class instead.
  31530. * 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.
  31531. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  31532. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  31533. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  31534. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  31535. */
  31536. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  31537. var options = {
  31538. position: position,
  31539. normal: normal,
  31540. size: size,
  31541. angle: angle
  31542. };
  31543. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  31544. };
  31545. // Skeletons
  31546. /**
  31547. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  31548. */
  31549. Mesh.prototype.setPositionsForCPUSkinning = function () {
  31550. if (!this._sourcePositions) {
  31551. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31552. if (!source) {
  31553. return this._sourcePositions;
  31554. }
  31555. this._sourcePositions = new Float32Array(source);
  31556. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31557. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  31558. }
  31559. }
  31560. return this._sourcePositions;
  31561. };
  31562. /**
  31563. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  31564. */
  31565. Mesh.prototype.setNormalsForCPUSkinning = function () {
  31566. if (!this._sourceNormals) {
  31567. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31568. if (!source) {
  31569. return this._sourceNormals;
  31570. }
  31571. this._sourceNormals = new Float32Array(source);
  31572. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31573. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  31574. }
  31575. }
  31576. return this._sourceNormals;
  31577. };
  31578. /**
  31579. * Updates the vertex buffer by applying transformation from the bones.
  31580. * Returns the Mesh.
  31581. *
  31582. * @param {skeleton} skeleton to apply
  31583. */
  31584. Mesh.prototype.applySkeleton = function (skeleton) {
  31585. if (!this.geometry) {
  31586. return this;
  31587. }
  31588. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  31589. return this;
  31590. }
  31591. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  31592. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31593. return this;
  31594. }
  31595. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31596. return this;
  31597. }
  31598. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31599. return this;
  31600. }
  31601. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31602. return this;
  31603. }
  31604. if (!this._sourcePositions) {
  31605. var submeshes = this.subMeshes.slice();
  31606. this.setPositionsForCPUSkinning();
  31607. this.subMeshes = submeshes;
  31608. }
  31609. if (!this._sourceNormals) {
  31610. this.setNormalsForCPUSkinning();
  31611. }
  31612. // positionsData checks for not being Float32Array will only pass at most once
  31613. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31614. if (!positionsData) {
  31615. return this;
  31616. }
  31617. if (!(positionsData instanceof Float32Array)) {
  31618. positionsData = new Float32Array(positionsData);
  31619. }
  31620. // normalsData checks for not being Float32Array will only pass at most once
  31621. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31622. if (!normalsData) {
  31623. return this;
  31624. }
  31625. if (!(normalsData instanceof Float32Array)) {
  31626. normalsData = new Float32Array(normalsData);
  31627. }
  31628. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31629. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31630. if (!matricesWeightsData || !matricesIndicesData) {
  31631. return this;
  31632. }
  31633. var needExtras = this.numBoneInfluencers > 4;
  31634. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31635. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31636. var skeletonMatrices = skeleton.getTransformMatrices(this);
  31637. var tempVector3 = BABYLON.Vector3.Zero();
  31638. var finalMatrix = new BABYLON.Matrix();
  31639. var tempMatrix = new BABYLON.Matrix();
  31640. var matWeightIdx = 0;
  31641. var inf;
  31642. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  31643. var weight;
  31644. for (inf = 0; inf < 4; inf++) {
  31645. weight = matricesWeightsData[matWeightIdx + inf];
  31646. if (weight > 0) {
  31647. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31648. finalMatrix.addToSelf(tempMatrix);
  31649. }
  31650. else
  31651. break;
  31652. }
  31653. if (needExtras) {
  31654. for (inf = 0; inf < 4; inf++) {
  31655. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31656. if (weight > 0) {
  31657. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31658. finalMatrix.addToSelf(tempMatrix);
  31659. }
  31660. else
  31661. break;
  31662. }
  31663. }
  31664. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  31665. tempVector3.toArray(positionsData, index);
  31666. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  31667. tempVector3.toArray(normalsData, index);
  31668. finalMatrix.reset();
  31669. }
  31670. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  31671. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  31672. return this;
  31673. };
  31674. // Tools
  31675. /**
  31676. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  31677. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  31678. */
  31679. Mesh.MinMax = function (meshes) {
  31680. var minVector = null;
  31681. var maxVector = null;
  31682. meshes.forEach(function (mesh, index, array) {
  31683. var boundingInfo = mesh.getBoundingInfo();
  31684. var boundingBox = boundingInfo.boundingBox;
  31685. if (!minVector || !maxVector) {
  31686. minVector = boundingBox.minimumWorld;
  31687. maxVector = boundingBox.maximumWorld;
  31688. }
  31689. else {
  31690. minVector.minimizeInPlace(boundingBox.minimumWorld);
  31691. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  31692. }
  31693. });
  31694. if (!minVector || !maxVector) {
  31695. return {
  31696. min: BABYLON.Vector3.Zero(),
  31697. max: BABYLON.Vector3.Zero()
  31698. };
  31699. }
  31700. return {
  31701. min: minVector,
  31702. max: maxVector
  31703. };
  31704. };
  31705. /**
  31706. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  31707. */
  31708. Mesh.Center = function (meshesOrMinMaxVector) {
  31709. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  31710. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  31711. };
  31712. /**
  31713. * Merge the array of meshes into a single mesh for performance reasons.
  31714. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  31715. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  31716. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  31717. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  31718. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  31719. */
  31720. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  31721. if (disposeSource === void 0) { disposeSource = true; }
  31722. var index;
  31723. if (!allow32BitsIndices) {
  31724. var totalVertices = 0;
  31725. // Counting vertices
  31726. for (index = 0; index < meshes.length; index++) {
  31727. if (meshes[index]) {
  31728. totalVertices += meshes[index].getTotalVertices();
  31729. if (totalVertices > 65536) {
  31730. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  31731. return null;
  31732. }
  31733. }
  31734. }
  31735. }
  31736. // Merge
  31737. var vertexData = null;
  31738. var otherVertexData;
  31739. var indiceArray = new Array();
  31740. var source = null;
  31741. for (index = 0; index < meshes.length; index++) {
  31742. if (meshes[index]) {
  31743. meshes[index].computeWorldMatrix(true);
  31744. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  31745. otherVertexData.transform(meshes[index].getWorldMatrix());
  31746. if (vertexData) {
  31747. vertexData.merge(otherVertexData);
  31748. }
  31749. else {
  31750. vertexData = otherVertexData;
  31751. source = meshes[index];
  31752. }
  31753. if (subdivideWithSubMeshes) {
  31754. indiceArray.push(meshes[index].getTotalIndices());
  31755. }
  31756. }
  31757. }
  31758. source = source;
  31759. if (!meshSubclass) {
  31760. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  31761. }
  31762. vertexData.applyToMesh(meshSubclass);
  31763. // Setting properties
  31764. meshSubclass.material = source.material;
  31765. meshSubclass.checkCollisions = source.checkCollisions;
  31766. // Cleaning
  31767. if (disposeSource) {
  31768. for (index = 0; index < meshes.length; index++) {
  31769. if (meshes[index]) {
  31770. meshes[index].dispose();
  31771. }
  31772. }
  31773. }
  31774. // Subdivide
  31775. if (subdivideWithSubMeshes) {
  31776. //-- Suppresions du submesh global
  31777. meshSubclass.releaseSubMeshes();
  31778. index = 0;
  31779. var offset = 0;
  31780. //-- aplique la subdivision en fonction du tableau d'indices
  31781. while (index < indiceArray.length) {
  31782. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  31783. offset += indiceArray[index];
  31784. index++;
  31785. }
  31786. }
  31787. return meshSubclass;
  31788. };
  31789. // Consts
  31790. Mesh._FRONTSIDE = 0;
  31791. Mesh._BACKSIDE = 1;
  31792. Mesh._DOUBLESIDE = 2;
  31793. Mesh._DEFAULTSIDE = 0;
  31794. Mesh._NO_CAP = 0;
  31795. Mesh._CAP_START = 1;
  31796. Mesh._CAP_END = 2;
  31797. Mesh._CAP_ALL = 3;
  31798. return Mesh;
  31799. }(BABYLON.AbstractMesh));
  31800. BABYLON.Mesh = Mesh;
  31801. })(BABYLON || (BABYLON = {}));
  31802. //# sourceMappingURL=babylon.mesh.js.map
  31803. "use strict";
  31804. var BABYLON;
  31805. (function (BABYLON) {
  31806. var BaseSubMesh = /** @class */ (function () {
  31807. function BaseSubMesh() {
  31808. }
  31809. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  31810. get: function () {
  31811. return this._materialEffect;
  31812. },
  31813. enumerable: true,
  31814. configurable: true
  31815. });
  31816. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  31817. if (defines === void 0) { defines = null; }
  31818. if (this._materialEffect === effect) {
  31819. if (!effect) {
  31820. this._materialDefines = null;
  31821. }
  31822. return;
  31823. }
  31824. this._materialDefines = defines;
  31825. this._materialEffect = effect;
  31826. };
  31827. return BaseSubMesh;
  31828. }());
  31829. BABYLON.BaseSubMesh = BaseSubMesh;
  31830. var SubMesh = /** @class */ (function (_super) {
  31831. __extends(SubMesh, _super);
  31832. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  31833. if (createBoundingBox === void 0) { createBoundingBox = true; }
  31834. var _this = _super.call(this) || this;
  31835. _this.materialIndex = materialIndex;
  31836. _this.verticesStart = verticesStart;
  31837. _this.verticesCount = verticesCount;
  31838. _this.indexStart = indexStart;
  31839. _this.indexCount = indexCount;
  31840. _this._renderId = 0;
  31841. _this._mesh = mesh;
  31842. _this._renderingMesh = renderingMesh || mesh;
  31843. mesh.subMeshes.push(_this);
  31844. _this._trianglePlanes = [];
  31845. _this._id = mesh.subMeshes.length - 1;
  31846. if (createBoundingBox) {
  31847. _this.refreshBoundingInfo();
  31848. mesh.computeWorldMatrix(true);
  31849. }
  31850. return _this;
  31851. }
  31852. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  31853. if (createBoundingBox === void 0) { createBoundingBox = true; }
  31854. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  31855. };
  31856. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  31857. get: function () {
  31858. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  31859. },
  31860. enumerable: true,
  31861. configurable: true
  31862. });
  31863. /**
  31864. * Returns the submesh BoudingInfo object.
  31865. */
  31866. SubMesh.prototype.getBoundingInfo = function () {
  31867. if (this.IsGlobal) {
  31868. return this._mesh.getBoundingInfo();
  31869. }
  31870. return this._boundingInfo;
  31871. };
  31872. /**
  31873. * Sets the submesh BoundingInfo.
  31874. * Return the SubMesh.
  31875. */
  31876. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  31877. this._boundingInfo = boundingInfo;
  31878. return this;
  31879. };
  31880. /**
  31881. * Returns the mesh of the current submesh.
  31882. */
  31883. SubMesh.prototype.getMesh = function () {
  31884. return this._mesh;
  31885. };
  31886. /**
  31887. * Returns the rendering mesh of the submesh.
  31888. */
  31889. SubMesh.prototype.getRenderingMesh = function () {
  31890. return this._renderingMesh;
  31891. };
  31892. /**
  31893. * Returns the submesh material.
  31894. */
  31895. SubMesh.prototype.getMaterial = function () {
  31896. var rootMaterial = this._renderingMesh.material;
  31897. if (rootMaterial === null || rootMaterial === undefined) {
  31898. return this._mesh.getScene().defaultMaterial;
  31899. }
  31900. else if (rootMaterial.getSubMaterial) {
  31901. var multiMaterial = rootMaterial;
  31902. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  31903. if (this._currentMaterial !== effectiveMaterial) {
  31904. this._currentMaterial = effectiveMaterial;
  31905. this._materialDefines = null;
  31906. }
  31907. return effectiveMaterial;
  31908. }
  31909. return rootMaterial;
  31910. };
  31911. // Methods
  31912. /**
  31913. * Sets a new updated BoundingInfo object to the submesh.
  31914. * Returns the SubMesh.
  31915. */
  31916. SubMesh.prototype.refreshBoundingInfo = function () {
  31917. this._lastColliderWorldVertices = null;
  31918. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  31919. return this;
  31920. }
  31921. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31922. if (!data) {
  31923. this._boundingInfo = this._mesh.getBoundingInfo();
  31924. return this;
  31925. }
  31926. var indices = this._renderingMesh.getIndices();
  31927. var extend;
  31928. //is this the only submesh?
  31929. if (this.indexStart === 0 && this.indexCount === indices.length) {
  31930. var boundingInfo = this._renderingMesh.getBoundingInfo();
  31931. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  31932. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  31933. }
  31934. else {
  31935. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  31936. }
  31937. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31938. return this;
  31939. };
  31940. SubMesh.prototype._checkCollision = function (collider) {
  31941. var boundingInfo = this.getBoundingInfo();
  31942. return boundingInfo._checkCollision(collider);
  31943. };
  31944. /**
  31945. * Updates the submesh BoundingInfo.
  31946. * Returns the Submesh.
  31947. */
  31948. SubMesh.prototype.updateBoundingInfo = function (world) {
  31949. var boundingInfo = this.getBoundingInfo();
  31950. if (!boundingInfo) {
  31951. this.refreshBoundingInfo();
  31952. boundingInfo = this.getBoundingInfo();
  31953. }
  31954. boundingInfo.update(world);
  31955. return this;
  31956. };
  31957. /**
  31958. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  31959. * Boolean returned.
  31960. */
  31961. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  31962. var boundingInfo = this.getBoundingInfo();
  31963. if (!boundingInfo) {
  31964. return false;
  31965. }
  31966. return boundingInfo.isInFrustum(frustumPlanes);
  31967. };
  31968. /**
  31969. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  31970. * Boolean returned.
  31971. */
  31972. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  31973. var boundingInfo = this.getBoundingInfo();
  31974. if (!boundingInfo) {
  31975. return false;
  31976. }
  31977. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  31978. };
  31979. /**
  31980. * Renders the submesh.
  31981. * Returns it.
  31982. */
  31983. SubMesh.prototype.render = function (enableAlphaMode) {
  31984. this._renderingMesh.render(this, enableAlphaMode);
  31985. return this;
  31986. };
  31987. /**
  31988. * Returns a new Index Buffer.
  31989. * Type returned : WebGLBuffer.
  31990. */
  31991. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31992. if (!this._linesIndexBuffer) {
  31993. var linesIndices = [];
  31994. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31995. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31996. }
  31997. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31998. this.linesIndexCount = linesIndices.length;
  31999. }
  32000. return this._linesIndexBuffer;
  32001. };
  32002. /**
  32003. * True is the passed Ray intersects the submesh bounding box.
  32004. * Boolean returned.
  32005. */
  32006. SubMesh.prototype.canIntersects = function (ray) {
  32007. var boundingInfo = this.getBoundingInfo();
  32008. if (!boundingInfo) {
  32009. return false;
  32010. }
  32011. return ray.intersectsBox(boundingInfo.boundingBox);
  32012. };
  32013. /**
  32014. * Returns an object IntersectionInfo.
  32015. */
  32016. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  32017. var intersectInfo = null;
  32018. var material = this.getMaterial();
  32019. if (!material) {
  32020. return null;
  32021. }
  32022. switch (material.fillMode) {
  32023. case BABYLON.Material.PointListDrawMode:
  32024. case BABYLON.Material.LineListDrawMode:
  32025. case BABYLON.Material.LineLoopDrawMode:
  32026. case BABYLON.Material.LineStripDrawMode:
  32027. case BABYLON.Material.TriangleFanDrawMode:
  32028. case BABYLON.Material.TriangleStripDrawMode:
  32029. return null;
  32030. }
  32031. // LineMesh first as it's also a Mesh...
  32032. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  32033. var lineMesh = this._mesh;
  32034. // Line test
  32035. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  32036. var p0 = positions[indices[index]];
  32037. var p1 = positions[indices[index + 1]];
  32038. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  32039. if (length < 0) {
  32040. continue;
  32041. }
  32042. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  32043. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  32044. if (fastCheck) {
  32045. break;
  32046. }
  32047. }
  32048. }
  32049. }
  32050. else {
  32051. // Triangles test
  32052. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  32053. var p0 = positions[indices[index]];
  32054. var p1 = positions[indices[index + 1]];
  32055. var p2 = positions[indices[index + 2]];
  32056. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  32057. if (currentIntersectInfo) {
  32058. if (currentIntersectInfo.distance < 0) {
  32059. continue;
  32060. }
  32061. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  32062. intersectInfo = currentIntersectInfo;
  32063. intersectInfo.faceId = index / 3;
  32064. if (fastCheck) {
  32065. break;
  32066. }
  32067. }
  32068. }
  32069. }
  32070. }
  32071. return intersectInfo;
  32072. };
  32073. SubMesh.prototype._rebuild = function () {
  32074. if (this._linesIndexBuffer) {
  32075. this._linesIndexBuffer = null;
  32076. }
  32077. };
  32078. // Clone
  32079. /**
  32080. * Creates a new Submesh from the passed Mesh.
  32081. */
  32082. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  32083. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  32084. if (!this.IsGlobal) {
  32085. var boundingInfo = this.getBoundingInfo();
  32086. if (!boundingInfo) {
  32087. return result;
  32088. }
  32089. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  32090. }
  32091. return result;
  32092. };
  32093. // Dispose
  32094. /**
  32095. * Disposes the Submesh.
  32096. * Returns nothing.
  32097. */
  32098. SubMesh.prototype.dispose = function () {
  32099. if (this._linesIndexBuffer) {
  32100. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  32101. this._linesIndexBuffer = null;
  32102. }
  32103. // Remove from mesh
  32104. var index = this._mesh.subMeshes.indexOf(this);
  32105. this._mesh.subMeshes.splice(index, 1);
  32106. };
  32107. // Statics
  32108. /**
  32109. * Creates a new Submesh from the passed parameters :
  32110. * - materialIndex (integer) : the index of the main mesh material.
  32111. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  32112. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  32113. * - mesh (Mesh) : the main mesh to create the submesh from.
  32114. * - renderingMesh (optional Mesh) : rendering mesh.
  32115. */
  32116. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  32117. var minVertexIndex = Number.MAX_VALUE;
  32118. var maxVertexIndex = -Number.MAX_VALUE;
  32119. renderingMesh = (renderingMesh || mesh);
  32120. var indices = renderingMesh.getIndices();
  32121. for (var index = startIndex; index < startIndex + indexCount; index++) {
  32122. var vertexIndex = indices[index];
  32123. if (vertexIndex < minVertexIndex)
  32124. minVertexIndex = vertexIndex;
  32125. if (vertexIndex > maxVertexIndex)
  32126. maxVertexIndex = vertexIndex;
  32127. }
  32128. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  32129. };
  32130. return SubMesh;
  32131. }(BaseSubMesh));
  32132. BABYLON.SubMesh = SubMesh;
  32133. })(BABYLON || (BABYLON = {}));
  32134. //# sourceMappingURL=babylon.subMesh.js.map
  32135. "use strict";
  32136. var __assign = (this && this.__assign) || Object.assign || function(t) {
  32137. for (var s, i = 1, n = arguments.length; i < n; i++) {
  32138. s = arguments[i];
  32139. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  32140. t[p] = s[p];
  32141. }
  32142. return t;
  32143. };
  32144. var BABYLON;
  32145. (function (BABYLON) {
  32146. /**
  32147. * Manages the defines for the Material.
  32148. */
  32149. var MaterialDefines = /** @class */ (function () {
  32150. function MaterialDefines() {
  32151. this._isDirty = true;
  32152. this._areLightsDirty = true;
  32153. this._areAttributesDirty = true;
  32154. this._areTexturesDirty = true;
  32155. this._areFresnelDirty = true;
  32156. this._areMiscDirty = true;
  32157. this._areImageProcessingDirty = true;
  32158. this._normals = false;
  32159. this._uvs = false;
  32160. this._needNormals = false;
  32161. this._needUVs = false;
  32162. }
  32163. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  32164. /**
  32165. * Specifies if the material needs to be re-calculated.
  32166. */
  32167. get: function () {
  32168. return this._isDirty;
  32169. },
  32170. enumerable: true,
  32171. configurable: true
  32172. });
  32173. /**
  32174. * Marks the material to indicate that it has been re-calculated.
  32175. */
  32176. MaterialDefines.prototype.markAsProcessed = function () {
  32177. this._isDirty = false;
  32178. this._areAttributesDirty = false;
  32179. this._areTexturesDirty = false;
  32180. this._areFresnelDirty = false;
  32181. this._areLightsDirty = false;
  32182. this._areMiscDirty = false;
  32183. this._areImageProcessingDirty = false;
  32184. };
  32185. /**
  32186. * Marks the material to indicate that it needs to be re-calculated.
  32187. */
  32188. MaterialDefines.prototype.markAsUnprocessed = function () {
  32189. this._isDirty = true;
  32190. };
  32191. /**
  32192. * Marks the material to indicate all of its defines need to be re-calculated.
  32193. */
  32194. MaterialDefines.prototype.markAllAsDirty = function () {
  32195. this._areTexturesDirty = true;
  32196. this._areAttributesDirty = true;
  32197. this._areLightsDirty = true;
  32198. this._areFresnelDirty = true;
  32199. this._areMiscDirty = true;
  32200. this._areImageProcessingDirty = true;
  32201. this._isDirty = true;
  32202. };
  32203. /**
  32204. * Marks the material to indicate that image processing needs to be re-calculated.
  32205. */
  32206. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  32207. this._areImageProcessingDirty = true;
  32208. this._isDirty = true;
  32209. };
  32210. /**
  32211. * Marks the material to indicate the lights need to be re-calculated.
  32212. */
  32213. MaterialDefines.prototype.markAsLightDirty = function () {
  32214. this._areLightsDirty = true;
  32215. this._isDirty = true;
  32216. };
  32217. /**
  32218. * Marks the attribute state as changed.
  32219. */
  32220. MaterialDefines.prototype.markAsAttributesDirty = function () {
  32221. this._areAttributesDirty = true;
  32222. this._isDirty = true;
  32223. };
  32224. /**
  32225. * Marks the texture state as changed.
  32226. */
  32227. MaterialDefines.prototype.markAsTexturesDirty = function () {
  32228. this._areTexturesDirty = true;
  32229. this._isDirty = true;
  32230. };
  32231. /**
  32232. * Marks the fresnel state as changed.
  32233. */
  32234. MaterialDefines.prototype.markAsFresnelDirty = function () {
  32235. this._areFresnelDirty = true;
  32236. this._isDirty = true;
  32237. };
  32238. /**
  32239. * Marks the misc state as changed.
  32240. */
  32241. MaterialDefines.prototype.markAsMiscDirty = function () {
  32242. this._areMiscDirty = true;
  32243. this._isDirty = true;
  32244. };
  32245. /**
  32246. * Rebuilds the material defines.
  32247. */
  32248. MaterialDefines.prototype.rebuild = function () {
  32249. if (this._keys) {
  32250. delete this._keys;
  32251. }
  32252. this._keys = [];
  32253. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  32254. var key = _a[_i];
  32255. if (key[0] === "_") {
  32256. continue;
  32257. }
  32258. this._keys.push(key);
  32259. }
  32260. };
  32261. /**
  32262. * Specifies if two material defines are equal.
  32263. * @param other - A material define instance to compare to.
  32264. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  32265. */
  32266. MaterialDefines.prototype.isEqual = function (other) {
  32267. if (this._keys.length !== other._keys.length) {
  32268. return false;
  32269. }
  32270. for (var index = 0; index < this._keys.length; index++) {
  32271. var prop = this._keys[index];
  32272. if (this[prop] !== other[prop]) {
  32273. return false;
  32274. }
  32275. }
  32276. return true;
  32277. };
  32278. /**
  32279. * Clones this instance's defines to another instance.
  32280. * @param other - material defines to clone values to.
  32281. */
  32282. MaterialDefines.prototype.cloneTo = function (other) {
  32283. if (this._keys.length !== other._keys.length) {
  32284. other._keys = this._keys.slice(0);
  32285. }
  32286. for (var index = 0; index < this._keys.length; index++) {
  32287. var prop = this._keys[index];
  32288. other[prop] = this[prop];
  32289. }
  32290. };
  32291. /**
  32292. * Resets the material define values.
  32293. */
  32294. MaterialDefines.prototype.reset = function () {
  32295. for (var index = 0; index < this._keys.length; index++) {
  32296. var prop = this._keys[index];
  32297. var type = typeof this[prop];
  32298. switch (type) {
  32299. case "number":
  32300. this[prop] = 0;
  32301. break;
  32302. case "string":
  32303. this[prop] = "";
  32304. break;
  32305. default:
  32306. this[prop] = false;
  32307. break;
  32308. }
  32309. }
  32310. };
  32311. /**
  32312. * Converts the material define values to a string.
  32313. * @returns - String of material define information.
  32314. */
  32315. MaterialDefines.prototype.toString = function () {
  32316. var result = "";
  32317. for (var index = 0; index < this._keys.length; index++) {
  32318. var prop = this._keys[index];
  32319. var value = this[prop];
  32320. var type = typeof value;
  32321. switch (type) {
  32322. case "number":
  32323. case "string":
  32324. result += "#define " + prop + " " + value + "\n";
  32325. break;
  32326. default:
  32327. if (value) {
  32328. result += "#define " + prop + "\n";
  32329. }
  32330. break;
  32331. }
  32332. }
  32333. return result;
  32334. };
  32335. return MaterialDefines;
  32336. }());
  32337. BABYLON.MaterialDefines = MaterialDefines;
  32338. /**
  32339. * This offers the main features of a material in BJS.
  32340. */
  32341. var Material = /** @class */ (function () {
  32342. /**
  32343. * Creates a material instance.
  32344. * @param name - The name of the material.
  32345. * @param scene - The BJS scene to reference.
  32346. * @param doNotAdd - Specifies if the material should be added to the scene.
  32347. */
  32348. function Material(name, scene, doNotAdd) {
  32349. /**
  32350. * Specifies if the ready state should be checked on each call.
  32351. */
  32352. this.checkReadyOnEveryCall = false;
  32353. /**
  32354. * Specifies if the ready state should be checked once.
  32355. */
  32356. this.checkReadyOnlyOnce = false;
  32357. /**
  32358. * The state of the material.
  32359. */
  32360. this.state = "";
  32361. /**
  32362. * The alpha value of the material.
  32363. */
  32364. this._alpha = 1.0;
  32365. /**
  32366. * Specifies if back face culling is enabled.
  32367. */
  32368. this._backFaceCulling = true;
  32369. /**
  32370. * Specifies if the material should be serialized.
  32371. */
  32372. this.doNotSerialize = false;
  32373. /**
  32374. * Specifies if the effect should be stored on sub meshes.
  32375. */
  32376. this.storeEffectOnSubMeshes = false;
  32377. /**
  32378. * An event triggered when the material is disposed.
  32379. */
  32380. this.onDisposeObservable = new BABYLON.Observable();
  32381. /**
  32382. * An event triggered when the material is bound.
  32383. */
  32384. this.onBindObservable = new BABYLON.Observable();
  32385. /**
  32386. * An event triggered when the material is unbound.
  32387. */
  32388. this.onUnBindObservable = new BABYLON.Observable();
  32389. /**
  32390. * Stores the value of the alpha mode.
  32391. */
  32392. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  32393. /**
  32394. * Stores the state of the need depth pre-pass value.
  32395. */
  32396. this._needDepthPrePass = false;
  32397. /**
  32398. * Specifies if depth writing should be disabled.
  32399. */
  32400. this.disableDepthWrite = false;
  32401. /**
  32402. * Specifies if depth writing should be forced.
  32403. */
  32404. this.forceDepthWrite = false;
  32405. /**
  32406. * Specifies if there should be a separate pass for culling.
  32407. */
  32408. this.separateCullingPass = false;
  32409. /**
  32410. * Stores the state specifing if fog should be enabled.
  32411. */
  32412. this._fogEnabled = true;
  32413. /**
  32414. * Stores the size of points.
  32415. */
  32416. this.pointSize = 1.0;
  32417. /**
  32418. * Stores the z offset value.
  32419. */
  32420. this.zOffset = 0;
  32421. /**
  32422. * Specifies if the material was previously ready.
  32423. */
  32424. this._wasPreviouslyReady = false;
  32425. /**
  32426. * Stores the fill mode state.
  32427. */
  32428. this._fillMode = Material.TriangleFillMode;
  32429. this.name = name;
  32430. this.id = name || BABYLON.Tools.RandomId();
  32431. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32432. if (this._scene.useRightHandedSystem) {
  32433. this.sideOrientation = Material.ClockWiseSideOrientation;
  32434. }
  32435. else {
  32436. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  32437. }
  32438. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  32439. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  32440. if (!doNotAdd) {
  32441. this._scene.materials.push(this);
  32442. }
  32443. }
  32444. Object.defineProperty(Material, "TriangleFillMode", {
  32445. /**
  32446. * Returns the triangle fill mode.
  32447. */
  32448. get: function () {
  32449. return Material._TriangleFillMode;
  32450. },
  32451. enumerable: true,
  32452. configurable: true
  32453. });
  32454. Object.defineProperty(Material, "WireFrameFillMode", {
  32455. /**
  32456. * Returns the wireframe mode.
  32457. */
  32458. get: function () {
  32459. return Material._WireFrameFillMode;
  32460. },
  32461. enumerable: true,
  32462. configurable: true
  32463. });
  32464. Object.defineProperty(Material, "PointFillMode", {
  32465. /**
  32466. * Returns the point fill mode.
  32467. */
  32468. get: function () {
  32469. return Material._PointFillMode;
  32470. },
  32471. enumerable: true,
  32472. configurable: true
  32473. });
  32474. Object.defineProperty(Material, "PointListDrawMode", {
  32475. /**
  32476. * Returns the point list draw mode.
  32477. */
  32478. get: function () {
  32479. return Material._PointListDrawMode;
  32480. },
  32481. enumerable: true,
  32482. configurable: true
  32483. });
  32484. Object.defineProperty(Material, "LineListDrawMode", {
  32485. /**
  32486. * Returns the line list draw mode.
  32487. */
  32488. get: function () {
  32489. return Material._LineListDrawMode;
  32490. },
  32491. enumerable: true,
  32492. configurable: true
  32493. });
  32494. Object.defineProperty(Material, "LineLoopDrawMode", {
  32495. /**
  32496. * Returns the line loop draw mode.
  32497. */
  32498. get: function () {
  32499. return Material._LineLoopDrawMode;
  32500. },
  32501. enumerable: true,
  32502. configurable: true
  32503. });
  32504. Object.defineProperty(Material, "LineStripDrawMode", {
  32505. /**
  32506. * Returns the line strip draw mode.
  32507. */
  32508. get: function () {
  32509. return Material._LineStripDrawMode;
  32510. },
  32511. enumerable: true,
  32512. configurable: true
  32513. });
  32514. Object.defineProperty(Material, "TriangleStripDrawMode", {
  32515. /**
  32516. * Returns the triangle strip draw mode.
  32517. */
  32518. get: function () {
  32519. return Material._TriangleStripDrawMode;
  32520. },
  32521. enumerable: true,
  32522. configurable: true
  32523. });
  32524. Object.defineProperty(Material, "TriangleFanDrawMode", {
  32525. /**
  32526. * Returns the triangle fan draw mode.
  32527. */
  32528. get: function () {
  32529. return Material._TriangleFanDrawMode;
  32530. },
  32531. enumerable: true,
  32532. configurable: true
  32533. });
  32534. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  32535. /**
  32536. * Returns the clock-wise side orientation.
  32537. */
  32538. get: function () {
  32539. return Material._ClockWiseSideOrientation;
  32540. },
  32541. enumerable: true,
  32542. configurable: true
  32543. });
  32544. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  32545. /**
  32546. * Returns the counter clock-wise side orientation.
  32547. */
  32548. get: function () {
  32549. return Material._CounterClockWiseSideOrientation;
  32550. },
  32551. enumerable: true,
  32552. configurable: true
  32553. });
  32554. Object.defineProperty(Material, "TextureDirtyFlag", {
  32555. /**
  32556. * Returns the dirty texture flag value.
  32557. */
  32558. get: function () {
  32559. return Material._TextureDirtyFlag;
  32560. },
  32561. enumerable: true,
  32562. configurable: true
  32563. });
  32564. Object.defineProperty(Material, "LightDirtyFlag", {
  32565. /**
  32566. * Returns the dirty light flag value.
  32567. */
  32568. get: function () {
  32569. return Material._LightDirtyFlag;
  32570. },
  32571. enumerable: true,
  32572. configurable: true
  32573. });
  32574. Object.defineProperty(Material, "FresnelDirtyFlag", {
  32575. /**
  32576. * Returns the dirty fresnel flag value.
  32577. */
  32578. get: function () {
  32579. return Material._FresnelDirtyFlag;
  32580. },
  32581. enumerable: true,
  32582. configurable: true
  32583. });
  32584. Object.defineProperty(Material, "AttributesDirtyFlag", {
  32585. /**
  32586. * Returns the dirty attributes flag value.
  32587. */
  32588. get: function () {
  32589. return Material._AttributesDirtyFlag;
  32590. },
  32591. enumerable: true,
  32592. configurable: true
  32593. });
  32594. Object.defineProperty(Material, "MiscDirtyFlag", {
  32595. /**
  32596. * Returns the dirty misc flag value.
  32597. */
  32598. get: function () {
  32599. return Material._MiscDirtyFlag;
  32600. },
  32601. enumerable: true,
  32602. configurable: true
  32603. });
  32604. Object.defineProperty(Material.prototype, "alpha", {
  32605. /**
  32606. * Gets the alpha value of the material.
  32607. */
  32608. get: function () {
  32609. return this._alpha;
  32610. },
  32611. /**
  32612. * Sets the alpha value of the material.
  32613. */
  32614. set: function (value) {
  32615. if (this._alpha === value) {
  32616. return;
  32617. }
  32618. this._alpha = value;
  32619. this.markAsDirty(Material.MiscDirtyFlag);
  32620. },
  32621. enumerable: true,
  32622. configurable: true
  32623. });
  32624. Object.defineProperty(Material.prototype, "backFaceCulling", {
  32625. /**
  32626. * Gets the back-face culling state.
  32627. */
  32628. get: function () {
  32629. return this._backFaceCulling;
  32630. },
  32631. /**
  32632. * Sets the back-face culling state.
  32633. */
  32634. set: function (value) {
  32635. if (this._backFaceCulling === value) {
  32636. return;
  32637. }
  32638. this._backFaceCulling = value;
  32639. this.markAsDirty(Material.TextureDirtyFlag);
  32640. },
  32641. enumerable: true,
  32642. configurable: true
  32643. });
  32644. Object.defineProperty(Material.prototype, "onDispose", {
  32645. /**
  32646. * Called during a dispose event.
  32647. */
  32648. set: function (callback) {
  32649. if (this._onDisposeObserver) {
  32650. this.onDisposeObservable.remove(this._onDisposeObserver);
  32651. }
  32652. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32653. },
  32654. enumerable: true,
  32655. configurable: true
  32656. });
  32657. Object.defineProperty(Material.prototype, "onBind", {
  32658. /**
  32659. * Called during a bind event.
  32660. */
  32661. set: function (callback) {
  32662. if (this._onBindObserver) {
  32663. this.onBindObservable.remove(this._onBindObserver);
  32664. }
  32665. this._onBindObserver = this.onBindObservable.add(callback);
  32666. },
  32667. enumerable: true,
  32668. configurable: true
  32669. });
  32670. Object.defineProperty(Material.prototype, "alphaMode", {
  32671. /**
  32672. * Gets the value of the alpha mode.
  32673. */
  32674. get: function () {
  32675. return this._alphaMode;
  32676. },
  32677. /**
  32678. * Sets the value of the alpha mode.
  32679. *
  32680. * | Value | Type | Description |
  32681. * | --- | --- | --- |
  32682. * | 0 | ALPHA_DISABLE | |
  32683. * | 1 | ALPHA_ADD | |
  32684. * | 2 | ALPHA_COMBINE | |
  32685. * | 3 | ALPHA_SUBTRACT | |
  32686. * | 4 | ALPHA_MULTIPLY | |
  32687. * | 5 | ALPHA_MAXIMIZED | |
  32688. * | 6 | ALPHA_ONEONE | |
  32689. * | 7 | ALPHA_PREMULTIPLIED | |
  32690. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  32691. * | 9 | ALPHA_INTERPOLATE | |
  32692. * | 10 | ALPHA_SCREENMODE | |
  32693. *
  32694. */
  32695. set: function (value) {
  32696. if (this._alphaMode === value) {
  32697. return;
  32698. }
  32699. this._alphaMode = value;
  32700. this.markAsDirty(Material.TextureDirtyFlag);
  32701. },
  32702. enumerable: true,
  32703. configurable: true
  32704. });
  32705. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  32706. /**
  32707. * Gets the depth pre-pass value.
  32708. */
  32709. get: function () {
  32710. return this._needDepthPrePass;
  32711. },
  32712. /**
  32713. * Sets the need depth pre-pass value.
  32714. */
  32715. set: function (value) {
  32716. if (this._needDepthPrePass === value) {
  32717. return;
  32718. }
  32719. this._needDepthPrePass = value;
  32720. if (this._needDepthPrePass) {
  32721. this.checkReadyOnEveryCall = true;
  32722. }
  32723. },
  32724. enumerable: true,
  32725. configurable: true
  32726. });
  32727. Object.defineProperty(Material.prototype, "fogEnabled", {
  32728. /**
  32729. * Gets the value of the fog enabled state.
  32730. */
  32731. get: function () {
  32732. return this._fogEnabled;
  32733. },
  32734. /**
  32735. * Sets the state for enabling fog.
  32736. */
  32737. set: function (value) {
  32738. if (this._fogEnabled === value) {
  32739. return;
  32740. }
  32741. this._fogEnabled = value;
  32742. this.markAsDirty(Material.MiscDirtyFlag);
  32743. },
  32744. enumerable: true,
  32745. configurable: true
  32746. });
  32747. Object.defineProperty(Material.prototype, "wireframe", {
  32748. /**
  32749. * Gets a value specifying if wireframe mode is enabled.
  32750. */
  32751. get: function () {
  32752. switch (this._fillMode) {
  32753. case Material.WireFrameFillMode:
  32754. case Material.LineListDrawMode:
  32755. case Material.LineLoopDrawMode:
  32756. case Material.LineStripDrawMode:
  32757. return true;
  32758. }
  32759. return this._scene.forceWireframe;
  32760. },
  32761. /**
  32762. * Sets the state of wireframe mode.
  32763. */
  32764. set: function (value) {
  32765. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  32766. },
  32767. enumerable: true,
  32768. configurable: true
  32769. });
  32770. Object.defineProperty(Material.prototype, "pointsCloud", {
  32771. /**
  32772. * Gets the value specifying if point clouds are enabled.
  32773. */
  32774. get: function () {
  32775. switch (this._fillMode) {
  32776. case Material.PointFillMode:
  32777. case Material.PointListDrawMode:
  32778. return true;
  32779. }
  32780. return this._scene.forcePointsCloud;
  32781. },
  32782. /**
  32783. * Sets the state of point cloud mode.
  32784. */
  32785. set: function (value) {
  32786. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  32787. },
  32788. enumerable: true,
  32789. configurable: true
  32790. });
  32791. Object.defineProperty(Material.prototype, "fillMode", {
  32792. /**
  32793. * Gets the material fill mode.
  32794. */
  32795. get: function () {
  32796. return this._fillMode;
  32797. },
  32798. /**
  32799. * Sets the material fill mode.
  32800. */
  32801. set: function (value) {
  32802. if (this._fillMode === value) {
  32803. return;
  32804. }
  32805. this._fillMode = value;
  32806. this.markAsDirty(Material.MiscDirtyFlag);
  32807. },
  32808. enumerable: true,
  32809. configurable: true
  32810. });
  32811. /**
  32812. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32813. * subclasses should override adding information pertainent to themselves.
  32814. * @returns - String with material information.
  32815. */
  32816. Material.prototype.toString = function (fullDetails) {
  32817. var ret = "Name: " + this.name;
  32818. if (fullDetails) {
  32819. }
  32820. return ret;
  32821. };
  32822. /**
  32823. * Gets the class name of the material.
  32824. * @returns - String with the class name of the material.
  32825. */
  32826. Material.prototype.getClassName = function () {
  32827. return "Material";
  32828. };
  32829. Object.defineProperty(Material.prototype, "isFrozen", {
  32830. /**
  32831. * Specifies if updates for the material been locked.
  32832. */
  32833. get: function () {
  32834. return this.checkReadyOnlyOnce;
  32835. },
  32836. enumerable: true,
  32837. configurable: true
  32838. });
  32839. /**
  32840. * Locks updates for the material.
  32841. */
  32842. Material.prototype.freeze = function () {
  32843. this.checkReadyOnlyOnce = true;
  32844. };
  32845. /**
  32846. * Unlocks updates for the material.
  32847. */
  32848. Material.prototype.unfreeze = function () {
  32849. this.checkReadyOnlyOnce = false;
  32850. };
  32851. /**
  32852. * Specifies if the material is ready to be used.
  32853. * @param mesh - BJS mesh.
  32854. * @param useInstances - Specifies if instances should be used.
  32855. * @returns - Boolean indicating if the material is ready to be used.
  32856. */
  32857. Material.prototype.isReady = function (mesh, useInstances) {
  32858. return true;
  32859. };
  32860. /**
  32861. * Specifies that the submesh is ready to be used.
  32862. * @param mesh - BJS mesh.
  32863. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  32864. * @param useInstances - Specifies that instances should be used.
  32865. * @returns - boolean indicating that the submesh is ready or not.
  32866. */
  32867. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32868. return false;
  32869. };
  32870. /**
  32871. * Returns the material effect.
  32872. * @returns - Nullable material effect.
  32873. */
  32874. Material.prototype.getEffect = function () {
  32875. return this._effect;
  32876. };
  32877. /**
  32878. * Returns the BJS scene.
  32879. * @returns - BJS Scene.
  32880. */
  32881. Material.prototype.getScene = function () {
  32882. return this._scene;
  32883. };
  32884. /**
  32885. * Specifies if the material will require alpha blending
  32886. * @returns - Boolean specifying if alpha blending is needed.
  32887. */
  32888. Material.prototype.needAlphaBlending = function () {
  32889. return (this.alpha < 1.0);
  32890. };
  32891. /**
  32892. * Specifies if the mesh will require alpha blending.
  32893. * @param mesh - BJS mesh.
  32894. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  32895. */
  32896. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  32897. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  32898. };
  32899. /**
  32900. * Specifies if this material should be rendered in alpha test mode.
  32901. * @returns - Boolean specifying if an alpha test is needed.
  32902. */
  32903. Material.prototype.needAlphaTesting = function () {
  32904. return false;
  32905. };
  32906. /**
  32907. * Gets the texture used for the alpha test.
  32908. * @returns - Nullable alpha test texture.
  32909. */
  32910. Material.prototype.getAlphaTestTexture = function () {
  32911. return null;
  32912. };
  32913. /**
  32914. * Marks the material to indicate that it needs to be re-calculated.
  32915. */
  32916. Material.prototype.markDirty = function () {
  32917. this._wasPreviouslyReady = false;
  32918. };
  32919. Material.prototype._preBind = function (effect, overrideOrientation) {
  32920. if (overrideOrientation === void 0) { overrideOrientation = null; }
  32921. var engine = this._scene.getEngine();
  32922. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  32923. var reverse = orientation === Material.ClockWiseSideOrientation;
  32924. engine.enableEffect(effect ? effect : this._effect);
  32925. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  32926. return reverse;
  32927. };
  32928. /**
  32929. * Binds the material to the mesh.
  32930. * @param world - World transformation matrix.
  32931. * @param mesh - Mesh to bind the material to.
  32932. */
  32933. Material.prototype.bind = function (world, mesh) {
  32934. };
  32935. /**
  32936. * Binds the submesh to the material.
  32937. * @param world - World transformation matrix.
  32938. * @param mesh - Mesh containing the submesh.
  32939. * @param subMesh - Submesh to bind the material to.
  32940. */
  32941. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32942. };
  32943. /**
  32944. * Binds the world matrix to the material.
  32945. * @param world - World transformation matrix.
  32946. */
  32947. Material.prototype.bindOnlyWorldMatrix = function (world) {
  32948. };
  32949. /**
  32950. * Binds the scene's uniform buffer to the effect.
  32951. * @param effect - Effect to bind to the scene uniform buffer.
  32952. * @param sceneUbo - Scene uniform buffer.
  32953. */
  32954. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  32955. sceneUbo.bindToEffect(effect, "Scene");
  32956. };
  32957. /**
  32958. * Binds the view matrix to the effect.
  32959. * @param effect - Effect to bind the view matrix to.
  32960. */
  32961. Material.prototype.bindView = function (effect) {
  32962. if (!this._useUBO) {
  32963. effect.setMatrix("view", this.getScene().getViewMatrix());
  32964. }
  32965. else {
  32966. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32967. }
  32968. };
  32969. /**
  32970. * Binds the view projection matrix to the effect.
  32971. * @param effect - Effect to bind the view projection matrix to.
  32972. */
  32973. Material.prototype.bindViewProjection = function (effect) {
  32974. if (!this._useUBO) {
  32975. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32976. }
  32977. else {
  32978. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32979. }
  32980. };
  32981. /**
  32982. * Specifies if material alpha testing should be turned on for the mesh.
  32983. * @param mesh - BJS mesh.
  32984. */
  32985. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  32986. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  32987. };
  32988. /**
  32989. * Processes to execute after binding the material to a mesh.
  32990. * @param mesh - BJS mesh.
  32991. */
  32992. Material.prototype._afterBind = function (mesh) {
  32993. this._scene._cachedMaterial = this;
  32994. if (mesh) {
  32995. this._scene._cachedVisibility = mesh.visibility;
  32996. }
  32997. else {
  32998. this._scene._cachedVisibility = 1;
  32999. }
  33000. if (mesh) {
  33001. this.onBindObservable.notifyObservers(mesh);
  33002. }
  33003. if (this.disableDepthWrite) {
  33004. var engine = this._scene.getEngine();
  33005. this._cachedDepthWriteState = engine.getDepthWrite();
  33006. engine.setDepthWrite(false);
  33007. }
  33008. };
  33009. /**
  33010. * Unbinds the material from the mesh.
  33011. */
  33012. Material.prototype.unbind = function () {
  33013. this.onUnBindObservable.notifyObservers(this);
  33014. if (this.disableDepthWrite) {
  33015. var engine = this._scene.getEngine();
  33016. engine.setDepthWrite(this._cachedDepthWriteState);
  33017. }
  33018. };
  33019. /**
  33020. * Gets the active textures from the material.
  33021. * @returns - Array of textures.
  33022. */
  33023. Material.prototype.getActiveTextures = function () {
  33024. return [];
  33025. };
  33026. /**
  33027. * Specifies if the material uses a texture.
  33028. * @param texture - Texture to check against the material.
  33029. * @returns - Boolean specifying if the material uses the texture.
  33030. */
  33031. Material.prototype.hasTexture = function (texture) {
  33032. return false;
  33033. };
  33034. /**
  33035. * Makes a duplicate of the material, and gives it a new name.
  33036. * @param name - Name to call the duplicated material.
  33037. * @returns - Nullable cloned material
  33038. */
  33039. Material.prototype.clone = function (name) {
  33040. return null;
  33041. };
  33042. /**
  33043. * Gets the meshes bound to the material.
  33044. * @returns - Array of meshes bound to the material.
  33045. */
  33046. Material.prototype.getBindedMeshes = function () {
  33047. var result = new Array();
  33048. for (var index = 0; index < this._scene.meshes.length; index++) {
  33049. var mesh = this._scene.meshes[index];
  33050. if (mesh.material === this) {
  33051. result.push(mesh);
  33052. }
  33053. }
  33054. return result;
  33055. };
  33056. /**
  33057. * Force shader compilation
  33058. * @param mesh - BJS mesh.
  33059. * @param onCompiled - function to execute once the material is compiled.
  33060. * @param options - options to pass to this function.
  33061. */
  33062. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  33063. var _this = this;
  33064. var localOptions = __assign({ clipPlane: false }, options);
  33065. var subMesh = new BABYLON.BaseSubMesh();
  33066. var scene = this.getScene();
  33067. var checkReady = function () {
  33068. if (!_this._scene || !_this._scene.getEngine()) {
  33069. return;
  33070. }
  33071. if (subMesh._materialDefines) {
  33072. subMesh._materialDefines._renderId = -1;
  33073. }
  33074. var clipPlaneState = scene.clipPlane;
  33075. if (localOptions.clipPlane) {
  33076. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  33077. }
  33078. if (_this.storeEffectOnSubMeshes) {
  33079. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  33080. if (onCompiled) {
  33081. onCompiled(_this);
  33082. }
  33083. }
  33084. else {
  33085. setTimeout(checkReady, 16);
  33086. }
  33087. }
  33088. else {
  33089. if (_this.isReady(mesh)) {
  33090. if (onCompiled) {
  33091. onCompiled(_this);
  33092. }
  33093. }
  33094. else {
  33095. setTimeout(checkReady, 16);
  33096. }
  33097. }
  33098. if (localOptions.clipPlane) {
  33099. scene.clipPlane = clipPlaneState;
  33100. }
  33101. };
  33102. checkReady();
  33103. };
  33104. /**
  33105. * Force shader compilation.
  33106. * @param mesh The mesh that will use this material
  33107. * @param options Additional options for compiling the shaders
  33108. * @returns A promise that resolves when the compilation completes
  33109. */
  33110. Material.prototype.forceCompilationAsync = function (mesh, options) {
  33111. var _this = this;
  33112. return new Promise(function (resolve) {
  33113. _this.forceCompilation(mesh, function () {
  33114. resolve();
  33115. }, options);
  33116. });
  33117. };
  33118. /**
  33119. * Marks a define in the material to indicate that it needs to be re-computed.
  33120. * @param flag - Material define flag.
  33121. */
  33122. Material.prototype.markAsDirty = function (flag) {
  33123. if (flag & Material.TextureDirtyFlag) {
  33124. this._markAllSubMeshesAsTexturesDirty();
  33125. }
  33126. if (flag & Material.LightDirtyFlag) {
  33127. this._markAllSubMeshesAsLightsDirty();
  33128. }
  33129. if (flag & Material.FresnelDirtyFlag) {
  33130. this._markAllSubMeshesAsFresnelDirty();
  33131. }
  33132. if (flag & Material.AttributesDirtyFlag) {
  33133. this._markAllSubMeshesAsAttributesDirty();
  33134. }
  33135. if (flag & Material.MiscDirtyFlag) {
  33136. this._markAllSubMeshesAsMiscDirty();
  33137. }
  33138. this.getScene().resetCachedMaterial();
  33139. };
  33140. /**
  33141. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  33142. * @param func - function which checks material defines against the submeshes.
  33143. */
  33144. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  33145. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  33146. var mesh = _a[_i];
  33147. if (!mesh.subMeshes) {
  33148. continue;
  33149. }
  33150. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  33151. var subMesh = _c[_b];
  33152. if (subMesh.getMaterial() !== this) {
  33153. continue;
  33154. }
  33155. if (!subMesh._materialDefines) {
  33156. continue;
  33157. }
  33158. func(subMesh._materialDefines);
  33159. }
  33160. }
  33161. };
  33162. /**
  33163. * Indicates that image processing needs to be re-calculated for all submeshes.
  33164. */
  33165. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  33166. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  33167. };
  33168. /**
  33169. * Indicates that textures need to be re-calculated for all submeshes.
  33170. */
  33171. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  33172. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  33173. };
  33174. /**
  33175. * Indicates that fresnel needs to be re-calculated for all submeshes.
  33176. */
  33177. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  33178. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  33179. };
  33180. /**
  33181. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  33182. */
  33183. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  33184. this._markAllSubMeshesAsDirty(function (defines) {
  33185. defines.markAsFresnelDirty();
  33186. defines.markAsMiscDirty();
  33187. });
  33188. };
  33189. /**
  33190. * Indicates that lights need to be re-calculated for all submeshes.
  33191. */
  33192. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  33193. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  33194. };
  33195. /**
  33196. * Indicates that attributes need to be re-calculated for all submeshes.
  33197. */
  33198. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  33199. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  33200. };
  33201. /**
  33202. * Indicates that misc needs to be re-calculated for all submeshes.
  33203. */
  33204. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  33205. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  33206. };
  33207. /**
  33208. * Indicates that textures and misc need to be re-calculated for all submeshes.
  33209. */
  33210. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  33211. this._markAllSubMeshesAsDirty(function (defines) {
  33212. defines.markAsTexturesDirty();
  33213. defines.markAsMiscDirty();
  33214. });
  33215. };
  33216. /**
  33217. * Disposes the material.
  33218. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  33219. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  33220. */
  33221. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  33222. // Animations
  33223. this.getScene().stopAnimation(this);
  33224. this.getScene().freeProcessedMaterials();
  33225. // Remove from scene
  33226. var index = this._scene.materials.indexOf(this);
  33227. if (index >= 0) {
  33228. this._scene.materials.splice(index, 1);
  33229. }
  33230. // Remove from meshes
  33231. for (index = 0; index < this._scene.meshes.length; index++) {
  33232. var mesh = this._scene.meshes[index];
  33233. if (mesh.material === this) {
  33234. mesh.material = null;
  33235. if (mesh.geometry) {
  33236. var geometry = (mesh.geometry);
  33237. if (this.storeEffectOnSubMeshes) {
  33238. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  33239. var subMesh = _a[_i];
  33240. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  33241. if (forceDisposeEffect && subMesh._materialEffect) {
  33242. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  33243. }
  33244. }
  33245. }
  33246. else {
  33247. geometry._releaseVertexArrayObject(this._effect);
  33248. }
  33249. }
  33250. }
  33251. }
  33252. this._uniformBuffer.dispose();
  33253. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  33254. if (forceDisposeEffect && this._effect) {
  33255. if (!this.storeEffectOnSubMeshes) {
  33256. this._scene.getEngine()._releaseEffect(this._effect);
  33257. }
  33258. this._effect = null;
  33259. }
  33260. // Callback
  33261. this.onDisposeObservable.notifyObservers(this);
  33262. this.onDisposeObservable.clear();
  33263. this.onBindObservable.clear();
  33264. this.onUnBindObservable.clear();
  33265. };
  33266. /**
  33267. * Serializes this material.
  33268. * @returns - serialized material object.
  33269. */
  33270. Material.prototype.serialize = function () {
  33271. return BABYLON.SerializationHelper.Serialize(this);
  33272. };
  33273. /**
  33274. * Creates a MultiMaterial from parse MultiMaterial data.
  33275. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  33276. * @param scene - BJS scene.
  33277. * @returns - MultiMaterial.
  33278. */
  33279. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  33280. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  33281. multiMaterial.id = parsedMultiMaterial.id;
  33282. if (BABYLON.Tags) {
  33283. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  33284. }
  33285. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  33286. var subMatId = parsedMultiMaterial.materials[matIndex];
  33287. if (subMatId) {
  33288. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  33289. }
  33290. else {
  33291. multiMaterial.subMaterials.push(null);
  33292. }
  33293. }
  33294. return multiMaterial;
  33295. };
  33296. /**
  33297. * Creates a material from parsed material data.
  33298. * @param parsedMaterial - Parsed material data.
  33299. * @param scene - BJS scene.
  33300. * @param rootUrl - Root URL containing the material information.
  33301. * @returns - Parsed material.
  33302. */
  33303. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  33304. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  33305. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  33306. }
  33307. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  33308. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  33309. if (!BABYLON.LegacyPBRMaterial) {
  33310. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  33311. return;
  33312. }
  33313. }
  33314. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  33315. return materialType.Parse(parsedMaterial, scene, rootUrl);
  33316. ;
  33317. };
  33318. // Triangle views
  33319. Material._TriangleFillMode = 0;
  33320. Material._WireFrameFillMode = 1;
  33321. Material._PointFillMode = 2;
  33322. // Draw modes
  33323. Material._PointListDrawMode = 3;
  33324. Material._LineListDrawMode = 4;
  33325. Material._LineLoopDrawMode = 5;
  33326. Material._LineStripDrawMode = 6;
  33327. Material._TriangleStripDrawMode = 7;
  33328. Material._TriangleFanDrawMode = 8;
  33329. /**
  33330. * Stores the clock-wise side orientation.
  33331. */
  33332. Material._ClockWiseSideOrientation = 0;
  33333. /**
  33334. * Stores the counter clock-wise side orientation.
  33335. */
  33336. Material._CounterClockWiseSideOrientation = 1;
  33337. /**
  33338. * The dirty texture flag value.
  33339. */
  33340. Material._TextureDirtyFlag = 1;
  33341. /**
  33342. * The dirty light flag value.
  33343. */
  33344. Material._LightDirtyFlag = 2;
  33345. /**
  33346. * The dirty fresnel flag value.
  33347. */
  33348. Material._FresnelDirtyFlag = 4;
  33349. /**
  33350. * The dirty attribute flag value.
  33351. */
  33352. Material._AttributesDirtyFlag = 8;
  33353. /**
  33354. * The dirty misc flag value.
  33355. */
  33356. Material._MiscDirtyFlag = 16;
  33357. __decorate([
  33358. BABYLON.serialize()
  33359. ], Material.prototype, "id", void 0);
  33360. __decorate([
  33361. BABYLON.serialize()
  33362. ], Material.prototype, "name", void 0);
  33363. __decorate([
  33364. BABYLON.serialize()
  33365. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  33366. __decorate([
  33367. BABYLON.serialize()
  33368. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  33369. __decorate([
  33370. BABYLON.serialize()
  33371. ], Material.prototype, "state", void 0);
  33372. __decorate([
  33373. BABYLON.serialize("alpha")
  33374. ], Material.prototype, "_alpha", void 0);
  33375. __decorate([
  33376. BABYLON.serialize("backFaceCulling")
  33377. ], Material.prototype, "_backFaceCulling", void 0);
  33378. __decorate([
  33379. BABYLON.serialize()
  33380. ], Material.prototype, "sideOrientation", void 0);
  33381. __decorate([
  33382. BABYLON.serialize("alphaMode")
  33383. ], Material.prototype, "_alphaMode", void 0);
  33384. __decorate([
  33385. BABYLON.serialize()
  33386. ], Material.prototype, "_needDepthPrePass", void 0);
  33387. __decorate([
  33388. BABYLON.serialize()
  33389. ], Material.prototype, "disableDepthWrite", void 0);
  33390. __decorate([
  33391. BABYLON.serialize()
  33392. ], Material.prototype, "forceDepthWrite", void 0);
  33393. __decorate([
  33394. BABYLON.serialize()
  33395. ], Material.prototype, "separateCullingPass", void 0);
  33396. __decorate([
  33397. BABYLON.serialize("fogEnabled")
  33398. ], Material.prototype, "_fogEnabled", void 0);
  33399. __decorate([
  33400. BABYLON.serialize()
  33401. ], Material.prototype, "pointSize", void 0);
  33402. __decorate([
  33403. BABYLON.serialize()
  33404. ], Material.prototype, "zOffset", void 0);
  33405. __decorate([
  33406. BABYLON.serialize()
  33407. ], Material.prototype, "wireframe", null);
  33408. __decorate([
  33409. BABYLON.serialize()
  33410. ], Material.prototype, "pointsCloud", null);
  33411. __decorate([
  33412. BABYLON.serialize()
  33413. ], Material.prototype, "fillMode", null);
  33414. return Material;
  33415. }());
  33416. BABYLON.Material = Material;
  33417. })(BABYLON || (BABYLON = {}));
  33418. //# sourceMappingURL=babylon.material.js.map
  33419. "use strict";
  33420. var BABYLON;
  33421. (function (BABYLON) {
  33422. var UniformBuffer = /** @class */ (function () {
  33423. /**
  33424. * Uniform buffer objects.
  33425. *
  33426. * Handles blocks of uniform on the GPU.
  33427. *
  33428. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  33429. *
  33430. * For more information, please refer to :
  33431. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  33432. */
  33433. function UniformBuffer(engine, data, dynamic) {
  33434. this._engine = engine;
  33435. this._noUBO = !engine.supportsUniformBuffers;
  33436. this._dynamic = dynamic;
  33437. this._data = data || [];
  33438. this._uniformLocations = {};
  33439. this._uniformSizes = {};
  33440. this._uniformLocationPointer = 0;
  33441. this._needSync = false;
  33442. if (this._noUBO) {
  33443. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  33444. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  33445. this.updateFloat = this._updateFloatForEffect;
  33446. this.updateFloat2 = this._updateFloat2ForEffect;
  33447. this.updateFloat3 = this._updateFloat3ForEffect;
  33448. this.updateFloat4 = this._updateFloat4ForEffect;
  33449. this.updateMatrix = this._updateMatrixForEffect;
  33450. this.updateVector3 = this._updateVector3ForEffect;
  33451. this.updateVector4 = this._updateVector4ForEffect;
  33452. this.updateColor3 = this._updateColor3ForEffect;
  33453. this.updateColor4 = this._updateColor4ForEffect;
  33454. }
  33455. else {
  33456. this._engine._uniformBuffers.push(this);
  33457. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  33458. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  33459. this.updateFloat = this._updateFloatForUniform;
  33460. this.updateFloat2 = this._updateFloat2ForUniform;
  33461. this.updateFloat3 = this._updateFloat3ForUniform;
  33462. this.updateFloat4 = this._updateFloat4ForUniform;
  33463. this.updateMatrix = this._updateMatrixForUniform;
  33464. this.updateVector3 = this._updateVector3ForUniform;
  33465. this.updateVector4 = this._updateVector4ForUniform;
  33466. this.updateColor3 = this._updateColor3ForUniform;
  33467. this.updateColor4 = this._updateColor4ForUniform;
  33468. }
  33469. }
  33470. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  33471. // Properties
  33472. /**
  33473. * Indicates if the buffer is using the WebGL2 UBO implementation,
  33474. * or just falling back on setUniformXXX calls.
  33475. */
  33476. get: function () {
  33477. return !this._noUBO;
  33478. },
  33479. enumerable: true,
  33480. configurable: true
  33481. });
  33482. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  33483. /**
  33484. * Indicates if the WebGL underlying uniform buffer is in sync
  33485. * with the javascript cache data.
  33486. */
  33487. get: function () {
  33488. return !this._needSync;
  33489. },
  33490. enumerable: true,
  33491. configurable: true
  33492. });
  33493. /**
  33494. * Indicates if the WebGL underlying uniform buffer is dynamic.
  33495. * Also, a dynamic UniformBuffer will disable cache verification and always
  33496. * update the underlying WebGL uniform buffer to the GPU.
  33497. */
  33498. UniformBuffer.prototype.isDynamic = function () {
  33499. return this._dynamic !== undefined;
  33500. };
  33501. /**
  33502. * The data cache on JS side.
  33503. */
  33504. UniformBuffer.prototype.getData = function () {
  33505. return this._bufferData;
  33506. };
  33507. /**
  33508. * The underlying WebGL Uniform buffer.
  33509. */
  33510. UniformBuffer.prototype.getBuffer = function () {
  33511. return this._buffer;
  33512. };
  33513. /**
  33514. * std140 layout specifies how to align data within an UBO structure.
  33515. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  33516. * for specs.
  33517. */
  33518. UniformBuffer.prototype._fillAlignment = function (size) {
  33519. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  33520. // and 4x4 matrices
  33521. // TODO : change if other types are used
  33522. var alignment;
  33523. if (size <= 2) {
  33524. alignment = size;
  33525. }
  33526. else {
  33527. alignment = 4;
  33528. }
  33529. if ((this._uniformLocationPointer % alignment) !== 0) {
  33530. var oldPointer = this._uniformLocationPointer;
  33531. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  33532. var diff = this._uniformLocationPointer - oldPointer;
  33533. for (var i = 0; i < diff; i++) {
  33534. this._data.push(0);
  33535. }
  33536. }
  33537. };
  33538. /**
  33539. * Adds an uniform in the buffer.
  33540. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  33541. * for the layout to be correct !
  33542. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33543. * @param {number|number[]} size Data size, or data directly.
  33544. */
  33545. UniformBuffer.prototype.addUniform = function (name, size) {
  33546. if (this._noUBO) {
  33547. return;
  33548. }
  33549. if (this._uniformLocations[name] !== undefined) {
  33550. // Already existing uniform
  33551. return;
  33552. }
  33553. // This function must be called in the order of the shader layout !
  33554. // size can be the size of the uniform, or data directly
  33555. var data;
  33556. if (size instanceof Array) {
  33557. data = size;
  33558. size = data.length;
  33559. }
  33560. else {
  33561. size = size;
  33562. data = [];
  33563. // Fill with zeros
  33564. for (var i = 0; i < size; i++) {
  33565. data.push(0);
  33566. }
  33567. }
  33568. this._fillAlignment(size);
  33569. this._uniformSizes[name] = size;
  33570. this._uniformLocations[name] = this._uniformLocationPointer;
  33571. this._uniformLocationPointer += size;
  33572. for (var i = 0; i < size; i++) {
  33573. this._data.push(data[i]);
  33574. }
  33575. this._needSync = true;
  33576. };
  33577. /**
  33578. * Wrapper for addUniform.
  33579. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33580. * @param {Matrix} mat A 4x4 matrix.
  33581. */
  33582. UniformBuffer.prototype.addMatrix = function (name, mat) {
  33583. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  33584. };
  33585. /**
  33586. * Wrapper for addUniform.
  33587. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33588. * @param {number} x
  33589. * @param {number} y
  33590. */
  33591. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  33592. var temp = [x, y];
  33593. this.addUniform(name, temp);
  33594. };
  33595. /**
  33596. * Wrapper for addUniform.
  33597. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33598. * @param {number} x
  33599. * @param {number} y
  33600. * @param {number} z
  33601. */
  33602. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  33603. var temp = [x, y, z];
  33604. this.addUniform(name, temp);
  33605. };
  33606. /**
  33607. * Wrapper for addUniform.
  33608. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33609. * @param {Color3} color
  33610. */
  33611. UniformBuffer.prototype.addColor3 = function (name, color) {
  33612. var temp = new Array();
  33613. color.toArray(temp);
  33614. this.addUniform(name, temp);
  33615. };
  33616. /**
  33617. * Wrapper for addUniform.
  33618. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33619. * @param {Color3} color
  33620. * @param {number} alpha
  33621. */
  33622. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  33623. var temp = new Array();
  33624. color.toArray(temp);
  33625. temp.push(alpha);
  33626. this.addUniform(name, temp);
  33627. };
  33628. /**
  33629. * Wrapper for addUniform.
  33630. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33631. * @param {Vector3} vector
  33632. */
  33633. UniformBuffer.prototype.addVector3 = function (name, vector) {
  33634. var temp = new Array();
  33635. vector.toArray(temp);
  33636. this.addUniform(name, temp);
  33637. };
  33638. /**
  33639. * Wrapper for addUniform.
  33640. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33641. */
  33642. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  33643. this.addUniform(name, 12);
  33644. };
  33645. /**
  33646. * Wrapper for addUniform.
  33647. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33648. */
  33649. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  33650. this.addUniform(name, 8);
  33651. };
  33652. /**
  33653. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  33654. */
  33655. UniformBuffer.prototype.create = function () {
  33656. if (this._noUBO) {
  33657. return;
  33658. }
  33659. if (this._buffer) {
  33660. return; // nothing to do
  33661. }
  33662. // See spec, alignment must be filled as a vec4
  33663. this._fillAlignment(4);
  33664. this._bufferData = new Float32Array(this._data);
  33665. this._rebuild();
  33666. this._needSync = true;
  33667. };
  33668. UniformBuffer.prototype._rebuild = function () {
  33669. if (this._noUBO) {
  33670. return;
  33671. }
  33672. if (this._dynamic) {
  33673. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  33674. }
  33675. else {
  33676. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  33677. }
  33678. };
  33679. /**
  33680. * Updates the WebGL Uniform Buffer on the GPU.
  33681. * If the `dynamic` flag is set to true, no cache comparison is done.
  33682. * Otherwise, the buffer will be updated only if the cache differs.
  33683. */
  33684. UniformBuffer.prototype.update = function () {
  33685. if (!this._buffer) {
  33686. this.create();
  33687. return;
  33688. }
  33689. if (!this._dynamic && !this._needSync) {
  33690. return;
  33691. }
  33692. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  33693. this._needSync = false;
  33694. };
  33695. /**
  33696. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  33697. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  33698. * @param {number[]|Float32Array} data Flattened data
  33699. * @param {number} size Size of the data.
  33700. */
  33701. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  33702. var location = this._uniformLocations[uniformName];
  33703. if (location === undefined) {
  33704. if (this._buffer) {
  33705. // Cannot add an uniform if the buffer is already created
  33706. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  33707. return;
  33708. }
  33709. this.addUniform(uniformName, size);
  33710. location = this._uniformLocations[uniformName];
  33711. }
  33712. if (!this._buffer) {
  33713. this.create();
  33714. }
  33715. if (!this._dynamic) {
  33716. // Cache for static uniform buffers
  33717. var changed = false;
  33718. for (var i = 0; i < size; i++) {
  33719. if (this._bufferData[location + i] !== data[i]) {
  33720. changed = true;
  33721. this._bufferData[location + i] = data[i];
  33722. }
  33723. }
  33724. this._needSync = this._needSync || changed;
  33725. }
  33726. else {
  33727. // No cache for dynamic
  33728. for (var i = 0; i < size; i++) {
  33729. this._bufferData[location + i] = data[i];
  33730. }
  33731. }
  33732. };
  33733. // Update methods
  33734. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  33735. // To match std140, matrix must be realigned
  33736. for (var i = 0; i < 3; i++) {
  33737. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  33738. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  33739. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  33740. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  33741. }
  33742. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  33743. };
  33744. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  33745. this._currentEffect.setMatrix3x3(name, matrix);
  33746. };
  33747. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  33748. this._currentEffect.setMatrix2x2(name, matrix);
  33749. };
  33750. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  33751. // To match std140, matrix must be realigned
  33752. for (var i = 0; i < 2; i++) {
  33753. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  33754. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  33755. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  33756. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  33757. }
  33758. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  33759. };
  33760. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  33761. this._currentEffect.setFloat(name, x);
  33762. };
  33763. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  33764. UniformBuffer._tempBuffer[0] = x;
  33765. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  33766. };
  33767. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  33768. if (suffix === void 0) { suffix = ""; }
  33769. this._currentEffect.setFloat2(name + suffix, x, y);
  33770. };
  33771. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  33772. if (suffix === void 0) { suffix = ""; }
  33773. UniformBuffer._tempBuffer[0] = x;
  33774. UniformBuffer._tempBuffer[1] = y;
  33775. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  33776. };
  33777. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  33778. if (suffix === void 0) { suffix = ""; }
  33779. this._currentEffect.setFloat3(name + suffix, x, y, z);
  33780. };
  33781. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  33782. if (suffix === void 0) { suffix = ""; }
  33783. UniformBuffer._tempBuffer[0] = x;
  33784. UniformBuffer._tempBuffer[1] = y;
  33785. UniformBuffer._tempBuffer[2] = z;
  33786. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  33787. };
  33788. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  33789. if (suffix === void 0) { suffix = ""; }
  33790. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  33791. };
  33792. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  33793. if (suffix === void 0) { suffix = ""; }
  33794. UniformBuffer._tempBuffer[0] = x;
  33795. UniformBuffer._tempBuffer[1] = y;
  33796. UniformBuffer._tempBuffer[2] = z;
  33797. UniformBuffer._tempBuffer[3] = w;
  33798. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  33799. };
  33800. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  33801. this._currentEffect.setMatrix(name, mat);
  33802. };
  33803. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  33804. this.updateUniform(name, mat.toArray(), 16);
  33805. };
  33806. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  33807. this._currentEffect.setVector3(name, vector);
  33808. };
  33809. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  33810. vector.toArray(UniformBuffer._tempBuffer);
  33811. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  33812. };
  33813. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  33814. this._currentEffect.setVector4(name, vector);
  33815. };
  33816. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  33817. vector.toArray(UniformBuffer._tempBuffer);
  33818. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  33819. };
  33820. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  33821. if (suffix === void 0) { suffix = ""; }
  33822. this._currentEffect.setColor3(name + suffix, color);
  33823. };
  33824. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  33825. if (suffix === void 0) { suffix = ""; }
  33826. color.toArray(UniformBuffer._tempBuffer);
  33827. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  33828. };
  33829. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  33830. if (suffix === void 0) { suffix = ""; }
  33831. this._currentEffect.setColor4(name + suffix, color, alpha);
  33832. };
  33833. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  33834. if (suffix === void 0) { suffix = ""; }
  33835. color.toArray(UniformBuffer._tempBuffer);
  33836. UniformBuffer._tempBuffer[3] = alpha;
  33837. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  33838. };
  33839. /**
  33840. * Sets a sampler uniform on the effect.
  33841. * @param {string} name Name of the sampler.
  33842. * @param {Texture} texture
  33843. */
  33844. UniformBuffer.prototype.setTexture = function (name, texture) {
  33845. this._currentEffect.setTexture(name, texture);
  33846. };
  33847. /**
  33848. * Directly updates the value of the uniform in the cache AND on the GPU.
  33849. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  33850. * @param {number[]|Float32Array} data Flattened data
  33851. */
  33852. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  33853. this.updateUniform(uniformName, data, data.length);
  33854. this.update();
  33855. };
  33856. /**
  33857. * Binds this uniform buffer to an effect.
  33858. * @param {Effect} effect
  33859. * @param {string} name Name of the uniform block in the shader.
  33860. */
  33861. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  33862. this._currentEffect = effect;
  33863. if (this._noUBO || !this._buffer) {
  33864. return;
  33865. }
  33866. effect.bindUniformBuffer(this._buffer, name);
  33867. };
  33868. /**
  33869. * Disposes the uniform buffer.
  33870. */
  33871. UniformBuffer.prototype.dispose = function () {
  33872. if (this._noUBO) {
  33873. return;
  33874. }
  33875. var index = this._engine._uniformBuffers.indexOf(this);
  33876. if (index !== -1) {
  33877. this._engine._uniformBuffers.splice(index, 1);
  33878. }
  33879. if (!this._buffer) {
  33880. return;
  33881. }
  33882. if (this._engine._releaseBuffer(this._buffer)) {
  33883. this._buffer = null;
  33884. }
  33885. };
  33886. // Pool for avoiding memory leaks
  33887. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  33888. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  33889. return UniformBuffer;
  33890. }());
  33891. BABYLON.UniformBuffer = UniformBuffer;
  33892. })(BABYLON || (BABYLON = {}));
  33893. //# sourceMappingURL=babylon.uniformBuffer.js.map
  33894. "use strict";
  33895. var BABYLON;
  33896. (function (BABYLON) {
  33897. var VertexData = /** @class */ (function () {
  33898. function VertexData() {
  33899. }
  33900. VertexData.prototype.set = function (data, kind) {
  33901. switch (kind) {
  33902. case BABYLON.VertexBuffer.PositionKind:
  33903. this.positions = data;
  33904. break;
  33905. case BABYLON.VertexBuffer.NormalKind:
  33906. this.normals = data;
  33907. break;
  33908. case BABYLON.VertexBuffer.TangentKind:
  33909. this.tangents = data;
  33910. break;
  33911. case BABYLON.VertexBuffer.UVKind:
  33912. this.uvs = data;
  33913. break;
  33914. case BABYLON.VertexBuffer.UV2Kind:
  33915. this.uvs2 = data;
  33916. break;
  33917. case BABYLON.VertexBuffer.UV3Kind:
  33918. this.uvs3 = data;
  33919. break;
  33920. case BABYLON.VertexBuffer.UV4Kind:
  33921. this.uvs4 = data;
  33922. break;
  33923. case BABYLON.VertexBuffer.UV5Kind:
  33924. this.uvs5 = data;
  33925. break;
  33926. case BABYLON.VertexBuffer.UV6Kind:
  33927. this.uvs6 = data;
  33928. break;
  33929. case BABYLON.VertexBuffer.ColorKind:
  33930. this.colors = data;
  33931. break;
  33932. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33933. this.matricesIndices = data;
  33934. break;
  33935. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33936. this.matricesWeights = data;
  33937. break;
  33938. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33939. this.matricesIndicesExtra = data;
  33940. break;
  33941. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33942. this.matricesWeightsExtra = data;
  33943. break;
  33944. }
  33945. };
  33946. /**
  33947. * Associates the vertexData to the passed Mesh.
  33948. * Sets it as updatable or not (default `false`).
  33949. * Returns the VertexData.
  33950. */
  33951. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33952. this._applyTo(mesh, updatable);
  33953. return this;
  33954. };
  33955. /**
  33956. * Associates the vertexData to the passed Geometry.
  33957. * Sets it as updatable or not (default `false`).
  33958. * Returns the VertexData.
  33959. */
  33960. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33961. this._applyTo(geometry, updatable);
  33962. return this;
  33963. };
  33964. /**
  33965. * Updates the associated mesh.
  33966. * Returns the VertexData.
  33967. */
  33968. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33969. this._update(mesh);
  33970. return this;
  33971. };
  33972. /**
  33973. * Updates the associated geometry.
  33974. * Returns the VertexData.
  33975. */
  33976. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33977. this._update(geometry);
  33978. return this;
  33979. };
  33980. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33981. if (updatable === void 0) { updatable = false; }
  33982. if (this.positions) {
  33983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33984. }
  33985. if (this.normals) {
  33986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33987. }
  33988. if (this.tangents) {
  33989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  33990. }
  33991. if (this.uvs) {
  33992. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33993. }
  33994. if (this.uvs2) {
  33995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33996. }
  33997. if (this.uvs3) {
  33998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33999. }
  34000. if (this.uvs4) {
  34001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  34002. }
  34003. if (this.uvs5) {
  34004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  34005. }
  34006. if (this.uvs6) {
  34007. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  34008. }
  34009. if (this.colors) {
  34010. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  34011. }
  34012. if (this.matricesIndices) {
  34013. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  34014. }
  34015. if (this.matricesWeights) {
  34016. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  34017. }
  34018. if (this.matricesIndicesExtra) {
  34019. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  34020. }
  34021. if (this.matricesWeightsExtra) {
  34022. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  34023. }
  34024. if (this.indices) {
  34025. meshOrGeometry.setIndices(this.indices, null, updatable);
  34026. }
  34027. return this;
  34028. };
  34029. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  34030. if (this.positions) {
  34031. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  34032. }
  34033. if (this.normals) {
  34034. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  34035. }
  34036. if (this.tangents) {
  34037. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  34038. }
  34039. if (this.uvs) {
  34040. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  34041. }
  34042. if (this.uvs2) {
  34043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  34044. }
  34045. if (this.uvs3) {
  34046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  34047. }
  34048. if (this.uvs4) {
  34049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  34050. }
  34051. if (this.uvs5) {
  34052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  34053. }
  34054. if (this.uvs6) {
  34055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  34056. }
  34057. if (this.colors) {
  34058. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  34059. }
  34060. if (this.matricesIndices) {
  34061. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  34062. }
  34063. if (this.matricesWeights) {
  34064. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  34065. }
  34066. if (this.matricesIndicesExtra) {
  34067. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  34068. }
  34069. if (this.matricesWeightsExtra) {
  34070. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  34071. }
  34072. if (this.indices) {
  34073. meshOrGeometry.setIndices(this.indices, null);
  34074. }
  34075. return this;
  34076. };
  34077. /**
  34078. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  34079. * Returns the VertexData.
  34080. */
  34081. VertexData.prototype.transform = function (matrix) {
  34082. var transformed = BABYLON.Vector3.Zero();
  34083. var index;
  34084. if (this.positions) {
  34085. var position = BABYLON.Vector3.Zero();
  34086. for (index = 0; index < this.positions.length; index += 3) {
  34087. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  34088. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  34089. this.positions[index] = transformed.x;
  34090. this.positions[index + 1] = transformed.y;
  34091. this.positions[index + 2] = transformed.z;
  34092. }
  34093. }
  34094. if (this.normals) {
  34095. var normal = BABYLON.Vector3.Zero();
  34096. for (index = 0; index < this.normals.length; index += 3) {
  34097. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  34098. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  34099. this.normals[index] = transformed.x;
  34100. this.normals[index + 1] = transformed.y;
  34101. this.normals[index + 2] = transformed.z;
  34102. }
  34103. }
  34104. if (this.tangents) {
  34105. var tangent = BABYLON.Vector4.Zero();
  34106. var tangentTransformed = BABYLON.Vector4.Zero();
  34107. for (index = 0; index < this.tangents.length; index += 4) {
  34108. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  34109. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  34110. this.tangents[index] = tangentTransformed.x;
  34111. this.tangents[index + 1] = tangentTransformed.y;
  34112. this.tangents[index + 2] = tangentTransformed.z;
  34113. this.tangents[index + 3] = tangentTransformed.w;
  34114. }
  34115. }
  34116. return this;
  34117. };
  34118. /**
  34119. * Merges the passed VertexData into the current one.
  34120. * Returns the modified VertexData.
  34121. */
  34122. VertexData.prototype.merge = function (other) {
  34123. this._validate();
  34124. other._validate();
  34125. if (!this.normals !== !other.normals ||
  34126. !this.tangents !== !other.tangents ||
  34127. !this.uvs !== !other.uvs ||
  34128. !this.uvs2 !== !other.uvs2 ||
  34129. !this.uvs3 !== !other.uvs3 ||
  34130. !this.uvs4 !== !other.uvs4 ||
  34131. !this.uvs5 !== !other.uvs5 ||
  34132. !this.uvs6 !== !other.uvs6 ||
  34133. !this.colors !== !other.colors ||
  34134. !this.matricesIndices !== !other.matricesIndices ||
  34135. !this.matricesWeights !== !other.matricesWeights ||
  34136. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  34137. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  34138. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  34139. }
  34140. if (other.indices) {
  34141. if (!this.indices) {
  34142. this.indices = [];
  34143. }
  34144. var offset = this.positions ? this.positions.length / 3 : 0;
  34145. for (var index = 0; index < other.indices.length; index++) {
  34146. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  34147. this.indices.push(other.indices[index] + offset);
  34148. }
  34149. }
  34150. this.positions = this._mergeElement(this.positions, other.positions);
  34151. this.normals = this._mergeElement(this.normals, other.normals);
  34152. this.tangents = this._mergeElement(this.tangents, other.tangents);
  34153. this.uvs = this._mergeElement(this.uvs, other.uvs);
  34154. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  34155. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  34156. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  34157. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  34158. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  34159. this.colors = this._mergeElement(this.colors, other.colors);
  34160. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  34161. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  34162. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  34163. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  34164. return this;
  34165. };
  34166. VertexData.prototype._mergeElement = function (source, other) {
  34167. if (!source) {
  34168. return other;
  34169. }
  34170. if (!other) {
  34171. return source;
  34172. }
  34173. var len = other.length + source.length;
  34174. var isSrcTypedArray = source instanceof Float32Array;
  34175. var isOthTypedArray = other instanceof Float32Array;
  34176. // use non-loop method when the source is Float32Array
  34177. if (isSrcTypedArray) {
  34178. var ret32 = new Float32Array(len);
  34179. ret32.set(source);
  34180. ret32.set(other, source.length);
  34181. return ret32;
  34182. // source is number[], when other is also use concat
  34183. }
  34184. else if (!isOthTypedArray) {
  34185. return source.concat(other);
  34186. // source is a number[], but other is a Float32Array, loop required
  34187. }
  34188. else {
  34189. var ret = source.slice(0); // copy source to a separate array
  34190. for (var i = 0, len = other.length; i < len; i++) {
  34191. ret.push(other[i]);
  34192. }
  34193. return ret;
  34194. }
  34195. };
  34196. VertexData.prototype._validate = function () {
  34197. if (!this.positions) {
  34198. throw new Error("Positions are required");
  34199. }
  34200. var getElementCount = function (kind, values) {
  34201. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  34202. if ((values.length % stride) !== 0) {
  34203. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  34204. }
  34205. return values.length / stride;
  34206. };
  34207. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  34208. var validateElementCount = function (kind, values) {
  34209. var elementCount = getElementCount(kind, values);
  34210. if (elementCount !== positionsElementCount) {
  34211. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  34212. }
  34213. };
  34214. if (this.normals)
  34215. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  34216. if (this.tangents)
  34217. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  34218. if (this.uvs)
  34219. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  34220. if (this.uvs2)
  34221. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  34222. if (this.uvs3)
  34223. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  34224. if (this.uvs4)
  34225. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  34226. if (this.uvs5)
  34227. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  34228. if (this.uvs6)
  34229. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  34230. if (this.colors)
  34231. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  34232. if (this.matricesIndices)
  34233. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  34234. if (this.matricesWeights)
  34235. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  34236. if (this.matricesIndicesExtra)
  34237. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  34238. if (this.matricesWeightsExtra)
  34239. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  34240. };
  34241. /**
  34242. * Serializes the VertexData.
  34243. * Returns a serialized object.
  34244. */
  34245. VertexData.prototype.serialize = function () {
  34246. var serializationObject = this.serialize();
  34247. if (this.positions) {
  34248. serializationObject.positions = this.positions;
  34249. }
  34250. if (this.normals) {
  34251. serializationObject.normals = this.normals;
  34252. }
  34253. if (this.tangents) {
  34254. serializationObject.tangents = this.tangents;
  34255. }
  34256. if (this.uvs) {
  34257. serializationObject.uvs = this.uvs;
  34258. }
  34259. if (this.uvs2) {
  34260. serializationObject.uvs2 = this.uvs2;
  34261. }
  34262. if (this.uvs3) {
  34263. serializationObject.uvs3 = this.uvs3;
  34264. }
  34265. if (this.uvs4) {
  34266. serializationObject.uvs4 = this.uvs4;
  34267. }
  34268. if (this.uvs5) {
  34269. serializationObject.uvs5 = this.uvs5;
  34270. }
  34271. if (this.uvs6) {
  34272. serializationObject.uvs6 = this.uvs6;
  34273. }
  34274. if (this.colors) {
  34275. serializationObject.colors = this.colors;
  34276. }
  34277. if (this.matricesIndices) {
  34278. serializationObject.matricesIndices = this.matricesIndices;
  34279. serializationObject.matricesIndices._isExpanded = true;
  34280. }
  34281. if (this.matricesWeights) {
  34282. serializationObject.matricesWeights = this.matricesWeights;
  34283. }
  34284. if (this.matricesIndicesExtra) {
  34285. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  34286. serializationObject.matricesIndicesExtra._isExpanded = true;
  34287. }
  34288. if (this.matricesWeightsExtra) {
  34289. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  34290. }
  34291. serializationObject.indices = this.indices;
  34292. return serializationObject;
  34293. };
  34294. // Statics
  34295. /**
  34296. * Returns the object VertexData associated to the passed mesh.
  34297. */
  34298. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  34299. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  34300. };
  34301. /**
  34302. * Returns the object VertexData associated to the passed geometry.
  34303. */
  34304. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  34305. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  34306. };
  34307. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  34308. var result = new VertexData();
  34309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34310. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  34311. }
  34312. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34313. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  34314. }
  34315. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34316. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  34317. }
  34318. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34319. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  34320. }
  34321. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34322. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  34323. }
  34324. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34325. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  34326. }
  34327. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34328. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  34329. }
  34330. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34331. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  34332. }
  34333. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34334. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  34335. }
  34336. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34337. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  34338. }
  34339. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34340. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  34341. }
  34342. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34343. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  34344. }
  34345. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  34346. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  34347. }
  34348. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  34349. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  34350. }
  34351. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  34352. return result;
  34353. };
  34354. /**
  34355. * Creates the vertexData of the Ribbon.
  34356. */
  34357. VertexData.CreateRibbon = function (options) {
  34358. var pathArray = options.pathArray;
  34359. var closeArray = options.closeArray || false;
  34360. var closePath = options.closePath || false;
  34361. var invertUV = options.invertUV || false;
  34362. var defaultOffset = Math.floor(pathArray[0].length / 2);
  34363. var offset = options.offset || defaultOffset;
  34364. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  34365. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34366. var customUV = options.uvs;
  34367. var customColors = options.colors;
  34368. var positions = [];
  34369. var indices = [];
  34370. var normals = [];
  34371. var uvs = [];
  34372. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  34373. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  34374. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  34375. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  34376. var minlg; // minimal length among all paths from pathArray
  34377. var lg = []; // array of path lengths : nb of vertex per path
  34378. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  34379. var p; // path iterator
  34380. var i; // point iterator
  34381. var j; // point iterator
  34382. // if single path in pathArray
  34383. if (pathArray.length < 2) {
  34384. var ar1 = [];
  34385. var ar2 = [];
  34386. for (i = 0; i < pathArray[0].length - offset; i++) {
  34387. ar1.push(pathArray[0][i]);
  34388. ar2.push(pathArray[0][i + offset]);
  34389. }
  34390. pathArray = [ar1, ar2];
  34391. }
  34392. // positions and horizontal distances (u)
  34393. var idc = 0;
  34394. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  34395. var path;
  34396. var l;
  34397. minlg = pathArray[0].length;
  34398. var vectlg;
  34399. var dist;
  34400. for (p = 0; p < pathArray.length; p++) {
  34401. uTotalDistance[p] = 0;
  34402. us[p] = [0];
  34403. path = pathArray[p];
  34404. l = path.length;
  34405. minlg = (minlg < l) ? minlg : l;
  34406. j = 0;
  34407. while (j < l) {
  34408. positions.push(path[j].x, path[j].y, path[j].z);
  34409. if (j > 0) {
  34410. vectlg = path[j].subtract(path[j - 1]).length();
  34411. dist = vectlg + uTotalDistance[p];
  34412. us[p].push(dist);
  34413. uTotalDistance[p] = dist;
  34414. }
  34415. j++;
  34416. }
  34417. if (closePath) {
  34418. j--;
  34419. positions.push(path[0].x, path[0].y, path[0].z);
  34420. vectlg = path[j].subtract(path[0]).length();
  34421. dist = vectlg + uTotalDistance[p];
  34422. us[p].push(dist);
  34423. uTotalDistance[p] = dist;
  34424. }
  34425. lg[p] = l + closePathCorr;
  34426. idx[p] = idc;
  34427. idc += (l + closePathCorr);
  34428. }
  34429. // vertical distances (v)
  34430. var path1;
  34431. var path2;
  34432. var vertex1 = null;
  34433. var vertex2 = null;
  34434. for (i = 0; i < minlg + closePathCorr; i++) {
  34435. vTotalDistance[i] = 0;
  34436. vs[i] = [0];
  34437. for (p = 0; p < pathArray.length - 1; p++) {
  34438. path1 = pathArray[p];
  34439. path2 = pathArray[p + 1];
  34440. if (i === minlg) {
  34441. vertex1 = path1[0];
  34442. vertex2 = path2[0];
  34443. }
  34444. else {
  34445. vertex1 = path1[i];
  34446. vertex2 = path2[i];
  34447. }
  34448. vectlg = vertex2.subtract(vertex1).length();
  34449. dist = vectlg + vTotalDistance[i];
  34450. vs[i].push(dist);
  34451. vTotalDistance[i] = dist;
  34452. }
  34453. if (closeArray && vertex2 && vertex1) {
  34454. path1 = pathArray[p];
  34455. path2 = pathArray[0];
  34456. if (i === minlg) {
  34457. vertex2 = path2[0];
  34458. }
  34459. vectlg = vertex2.subtract(vertex1).length();
  34460. dist = vectlg + vTotalDistance[i];
  34461. vTotalDistance[i] = dist;
  34462. }
  34463. }
  34464. // uvs
  34465. var u;
  34466. var v;
  34467. if (customUV) {
  34468. for (p = 0; p < customUV.length; p++) {
  34469. uvs.push(customUV[p].x, customUV[p].y);
  34470. }
  34471. }
  34472. else {
  34473. for (p = 0; p < pathArray.length; p++) {
  34474. for (i = 0; i < minlg + closePathCorr; i++) {
  34475. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  34476. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  34477. if (invertUV) {
  34478. uvs.push(v, u);
  34479. }
  34480. else {
  34481. uvs.push(u, v);
  34482. }
  34483. }
  34484. }
  34485. }
  34486. // indices
  34487. p = 0; // path index
  34488. var pi = 0; // positions array index
  34489. var l1 = lg[p] - 1; // path1 length
  34490. var l2 = lg[p + 1] - 1; // path2 length
  34491. var min = (l1 < l2) ? l1 : l2; // current path stop index
  34492. var shft = idx[1] - idx[0]; // shift
  34493. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  34494. while (pi <= min && p < path1nb) {
  34495. // 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
  34496. indices.push(pi, pi + shft, pi + 1);
  34497. indices.push(pi + shft + 1, pi + 1, pi + shft);
  34498. pi += 1;
  34499. if (pi === min) {
  34500. p++;
  34501. if (p === lg.length - 1) {
  34502. shft = idx[0] - idx[p];
  34503. l1 = lg[p] - 1;
  34504. l2 = lg[0] - 1;
  34505. }
  34506. else {
  34507. shft = idx[p + 1] - idx[p];
  34508. l1 = lg[p] - 1;
  34509. l2 = lg[p + 1] - 1;
  34510. }
  34511. pi = idx[p];
  34512. min = (l1 < l2) ? l1 + pi : l2 + pi;
  34513. }
  34514. }
  34515. // normals
  34516. VertexData.ComputeNormals(positions, indices, normals);
  34517. if (closePath) {
  34518. var indexFirst = 0;
  34519. var indexLast = 0;
  34520. for (p = 0; p < pathArray.length; p++) {
  34521. indexFirst = idx[p] * 3;
  34522. if (p + 1 < pathArray.length) {
  34523. indexLast = (idx[p + 1] - 1) * 3;
  34524. }
  34525. else {
  34526. indexLast = normals.length - 3;
  34527. }
  34528. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  34529. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  34530. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  34531. normals[indexLast] = normals[indexFirst];
  34532. normals[indexLast + 1] = normals[indexFirst + 1];
  34533. normals[indexLast + 2] = normals[indexFirst + 2];
  34534. }
  34535. }
  34536. // sides
  34537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34538. // Colors
  34539. var colors = null;
  34540. if (customColors) {
  34541. colors = new Float32Array(customColors.length * 4);
  34542. for (var c = 0; c < customColors.length; c++) {
  34543. colors[c * 4] = customColors[c].r;
  34544. colors[c * 4 + 1] = customColors[c].g;
  34545. colors[c * 4 + 2] = customColors[c].b;
  34546. colors[c * 4 + 3] = customColors[c].a;
  34547. }
  34548. }
  34549. // Result
  34550. var vertexData = new VertexData();
  34551. var positions32 = new Float32Array(positions);
  34552. var normals32 = new Float32Array(normals);
  34553. var uvs32 = new Float32Array(uvs);
  34554. vertexData.indices = indices;
  34555. vertexData.positions = positions32;
  34556. vertexData.normals = normals32;
  34557. vertexData.uvs = uvs32;
  34558. if (colors) {
  34559. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  34560. }
  34561. if (closePath) {
  34562. vertexData._idx = idx;
  34563. }
  34564. return vertexData;
  34565. };
  34566. /**
  34567. * Creates the VertexData of the Box.
  34568. */
  34569. VertexData.CreateBox = function (options) {
  34570. var normalsSource = [
  34571. new BABYLON.Vector3(0, 0, 1),
  34572. new BABYLON.Vector3(0, 0, -1),
  34573. new BABYLON.Vector3(1, 0, 0),
  34574. new BABYLON.Vector3(-1, 0, 0),
  34575. new BABYLON.Vector3(0, 1, 0),
  34576. new BABYLON.Vector3(0, -1, 0)
  34577. ];
  34578. var indices = [];
  34579. var positions = [];
  34580. var normals = [];
  34581. var uvs = [];
  34582. var width = options.width || options.size || 1;
  34583. var height = options.height || options.size || 1;
  34584. var depth = options.depth || options.size || 1;
  34585. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34586. var faceUV = options.faceUV || new Array(6);
  34587. var faceColors = options.faceColors;
  34588. var colors = [];
  34589. // default face colors and UV if undefined
  34590. for (var f = 0; f < 6; f++) {
  34591. if (faceUV[f] === undefined) {
  34592. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34593. }
  34594. if (faceColors && faceColors[f] === undefined) {
  34595. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34596. }
  34597. }
  34598. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  34599. // Create each face in turn.
  34600. for (var index = 0; index < normalsSource.length; index++) {
  34601. var normal = normalsSource[index];
  34602. // Get two vectors perpendicular to the face normal and to each other.
  34603. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  34604. var side2 = BABYLON.Vector3.Cross(normal, side1);
  34605. // Six indices (two triangles) per face.
  34606. var verticesLength = positions.length / 3;
  34607. indices.push(verticesLength);
  34608. indices.push(verticesLength + 1);
  34609. indices.push(verticesLength + 2);
  34610. indices.push(verticesLength);
  34611. indices.push(verticesLength + 2);
  34612. indices.push(verticesLength + 3);
  34613. // Four vertices per face.
  34614. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  34615. positions.push(vertex.x, vertex.y, vertex.z);
  34616. normals.push(normal.x, normal.y, normal.z);
  34617. uvs.push(faceUV[index].z, faceUV[index].w);
  34618. if (faceColors) {
  34619. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  34620. }
  34621. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  34622. positions.push(vertex.x, vertex.y, vertex.z);
  34623. normals.push(normal.x, normal.y, normal.z);
  34624. uvs.push(faceUV[index].x, faceUV[index].w);
  34625. if (faceColors) {
  34626. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  34627. }
  34628. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  34629. positions.push(vertex.x, vertex.y, vertex.z);
  34630. normals.push(normal.x, normal.y, normal.z);
  34631. uvs.push(faceUV[index].x, faceUV[index].y);
  34632. if (faceColors) {
  34633. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  34634. }
  34635. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  34636. positions.push(vertex.x, vertex.y, vertex.z);
  34637. normals.push(normal.x, normal.y, normal.z);
  34638. uvs.push(faceUV[index].z, faceUV[index].y);
  34639. if (faceColors) {
  34640. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  34641. }
  34642. }
  34643. // sides
  34644. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34645. // Result
  34646. var vertexData = new VertexData();
  34647. vertexData.indices = indices;
  34648. vertexData.positions = positions;
  34649. vertexData.normals = normals;
  34650. vertexData.uvs = uvs;
  34651. if (faceColors) {
  34652. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34653. vertexData.colors = totalColors;
  34654. }
  34655. return vertexData;
  34656. };
  34657. /**
  34658. * Creates the VertexData of the Sphere.
  34659. */
  34660. VertexData.CreateSphere = function (options) {
  34661. var segments = options.segments || 32;
  34662. var diameterX = options.diameterX || options.diameter || 1;
  34663. var diameterY = options.diameterY || options.diameter || 1;
  34664. var diameterZ = options.diameterZ || options.diameter || 1;
  34665. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34666. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  34667. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34668. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  34669. var totalZRotationSteps = 2 + segments;
  34670. var totalYRotationSteps = 2 * totalZRotationSteps;
  34671. var indices = [];
  34672. var positions = [];
  34673. var normals = [];
  34674. var uvs = [];
  34675. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  34676. var normalizedZ = zRotationStep / totalZRotationSteps;
  34677. var angleZ = normalizedZ * Math.PI * slice;
  34678. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  34679. var normalizedY = yRotationStep / totalYRotationSteps;
  34680. var angleY = normalizedY * Math.PI * 2 * arc;
  34681. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  34682. var rotationY = BABYLON.Matrix.RotationY(angleY);
  34683. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  34684. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  34685. var vertex = complete.multiply(radius);
  34686. var normal = complete.divide(radius).normalize();
  34687. positions.push(vertex.x, vertex.y, vertex.z);
  34688. normals.push(normal.x, normal.y, normal.z);
  34689. uvs.push(normalizedY, normalizedZ);
  34690. }
  34691. if (zRotationStep > 0) {
  34692. var verticesCount = positions.length / 3;
  34693. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  34694. indices.push((firstIndex));
  34695. indices.push((firstIndex + 1));
  34696. indices.push(firstIndex + totalYRotationSteps + 1);
  34697. indices.push((firstIndex + totalYRotationSteps + 1));
  34698. indices.push((firstIndex + 1));
  34699. indices.push((firstIndex + totalYRotationSteps + 2));
  34700. }
  34701. }
  34702. }
  34703. // Sides
  34704. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34705. // Result
  34706. var vertexData = new VertexData();
  34707. vertexData.indices = indices;
  34708. vertexData.positions = positions;
  34709. vertexData.normals = normals;
  34710. vertexData.uvs = uvs;
  34711. return vertexData;
  34712. };
  34713. /**
  34714. * Creates the VertexData of the Cylinder or Cone.
  34715. */
  34716. VertexData.CreateCylinder = function (options) {
  34717. var height = options.height || 2;
  34718. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  34719. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  34720. var tessellation = options.tessellation || 24;
  34721. var subdivisions = options.subdivisions || 1;
  34722. var hasRings = options.hasRings ? true : false;
  34723. var enclose = options.enclose ? true : false;
  34724. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34725. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34726. var faceUV = options.faceUV || new Array(3);
  34727. var faceColors = options.faceColors;
  34728. // default face colors and UV if undefined
  34729. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  34730. var ringNb = (hasRings) ? subdivisions : 1;
  34731. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  34732. var f;
  34733. for (f = 0; f < surfaceNb; f++) {
  34734. if (faceColors && faceColors[f] === undefined) {
  34735. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34736. }
  34737. }
  34738. for (f = 0; f < surfaceNb; f++) {
  34739. if (faceUV && faceUV[f] === undefined) {
  34740. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34741. }
  34742. }
  34743. var indices = new Array();
  34744. var positions = new Array();
  34745. var normals = new Array();
  34746. var uvs = new Array();
  34747. var colors = new Array();
  34748. var angle_step = Math.PI * 2 * arc / tessellation;
  34749. var angle;
  34750. var h;
  34751. var radius;
  34752. var tan = (diameterBottom - diameterTop) / 2 / height;
  34753. var ringVertex = BABYLON.Vector3.Zero();
  34754. var ringNormal = BABYLON.Vector3.Zero();
  34755. var ringFirstVertex = BABYLON.Vector3.Zero();
  34756. var ringFirstNormal = BABYLON.Vector3.Zero();
  34757. var quadNormal = BABYLON.Vector3.Zero();
  34758. var Y = BABYLON.Axis.Y;
  34759. // positions, normals, uvs
  34760. var i;
  34761. var j;
  34762. var r;
  34763. var ringIdx = 1;
  34764. var s = 1; // surface index
  34765. var cs = 0;
  34766. var v = 0;
  34767. for (i = 0; i <= subdivisions; i++) {
  34768. h = i / subdivisions;
  34769. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  34770. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  34771. for (r = 0; r < ringIdx; r++) {
  34772. if (hasRings) {
  34773. s += r;
  34774. }
  34775. if (enclose) {
  34776. s += 2 * r;
  34777. }
  34778. for (j = 0; j <= tessellation; j++) {
  34779. angle = j * angle_step;
  34780. // position
  34781. ringVertex.x = Math.cos(-angle) * radius;
  34782. ringVertex.y = -height / 2 + h * height;
  34783. ringVertex.z = Math.sin(-angle) * radius;
  34784. // normal
  34785. if (diameterTop === 0 && i === subdivisions) {
  34786. // if no top cap, reuse former normals
  34787. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  34788. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  34789. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  34790. }
  34791. else {
  34792. ringNormal.x = ringVertex.x;
  34793. ringNormal.z = ringVertex.z;
  34794. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  34795. ringNormal.normalize();
  34796. }
  34797. // keep first ring vertex values for enclose
  34798. if (j === 0) {
  34799. ringFirstVertex.copyFrom(ringVertex);
  34800. ringFirstNormal.copyFrom(ringNormal);
  34801. }
  34802. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  34803. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  34804. if (hasRings) {
  34805. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  34806. }
  34807. else {
  34808. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  34809. }
  34810. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  34811. if (faceColors) {
  34812. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  34813. }
  34814. }
  34815. // if enclose, add four vertices and their dedicated normals
  34816. if (arc !== 1 && enclose) {
  34817. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  34818. positions.push(0, ringVertex.y, 0);
  34819. positions.push(0, ringVertex.y, 0);
  34820. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  34821. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  34822. quadNormal.normalize();
  34823. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  34824. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  34825. quadNormal.normalize();
  34826. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  34827. if (hasRings) {
  34828. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  34829. }
  34830. else {
  34831. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  34832. }
  34833. uvs.push(faceUV[s + 1].x, v);
  34834. uvs.push(faceUV[s + 1].z, v);
  34835. if (hasRings) {
  34836. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  34837. }
  34838. else {
  34839. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  34840. }
  34841. uvs.push(faceUV[s + 2].x, v);
  34842. uvs.push(faceUV[s + 2].z, v);
  34843. if (faceColors) {
  34844. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  34845. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  34846. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  34847. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  34848. }
  34849. }
  34850. if (cs !== s) {
  34851. cs = s;
  34852. }
  34853. }
  34854. }
  34855. // indices
  34856. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  34857. var s;
  34858. i = 0;
  34859. for (s = 0; s < subdivisions; s++) {
  34860. var i0 = 0;
  34861. var i1 = 0;
  34862. var i2 = 0;
  34863. var i3 = 0;
  34864. for (j = 0; j < tessellation; j++) {
  34865. i0 = i * (e + 1) + j;
  34866. i1 = (i + 1) * (e + 1) + j;
  34867. i2 = i * (e + 1) + (j + 1);
  34868. i3 = (i + 1) * (e + 1) + (j + 1);
  34869. indices.push(i0, i1, i2);
  34870. indices.push(i3, i2, i1);
  34871. }
  34872. if (arc !== 1 && enclose) {
  34873. indices.push(i0 + 2, i1 + 2, i2 + 2);
  34874. indices.push(i3 + 2, i2 + 2, i1 + 2);
  34875. indices.push(i0 + 4, i1 + 4, i2 + 4);
  34876. indices.push(i3 + 4, i2 + 4, i1 + 4);
  34877. }
  34878. i = (hasRings) ? (i + 2) : (i + 1);
  34879. }
  34880. // Caps
  34881. var createCylinderCap = function (isTop) {
  34882. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  34883. if (radius === 0) {
  34884. return;
  34885. }
  34886. // Cap positions, normals & uvs
  34887. var angle;
  34888. var circleVector;
  34889. var i;
  34890. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  34891. var c = null;
  34892. if (faceColors) {
  34893. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  34894. }
  34895. // cap center
  34896. var vbase = positions.length / 3;
  34897. var offset = isTop ? height / 2 : -height / 2;
  34898. var center = new BABYLON.Vector3(0, offset, 0);
  34899. positions.push(center.x, center.y, center.z);
  34900. normals.push(0, isTop ? 1 : -1, 0);
  34901. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  34902. if (c) {
  34903. colors.push(c.r, c.g, c.b, c.a);
  34904. }
  34905. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  34906. for (i = 0; i <= tessellation; i++) {
  34907. angle = Math.PI * 2 * i * arc / tessellation;
  34908. var cos = Math.cos(-angle);
  34909. var sin = Math.sin(-angle);
  34910. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  34911. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  34912. positions.push(circleVector.x, circleVector.y, circleVector.z);
  34913. normals.push(0, isTop ? 1 : -1, 0);
  34914. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  34915. if (c) {
  34916. colors.push(c.r, c.g, c.b, c.a);
  34917. }
  34918. }
  34919. // Cap indices
  34920. for (i = 0; i < tessellation; i++) {
  34921. if (!isTop) {
  34922. indices.push(vbase);
  34923. indices.push(vbase + (i + 1));
  34924. indices.push(vbase + (i + 2));
  34925. }
  34926. else {
  34927. indices.push(vbase);
  34928. indices.push(vbase + (i + 2));
  34929. indices.push(vbase + (i + 1));
  34930. }
  34931. }
  34932. };
  34933. // add caps to geometry
  34934. createCylinderCap(false);
  34935. createCylinderCap(true);
  34936. // Sides
  34937. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34938. var vertexData = new VertexData();
  34939. vertexData.indices = indices;
  34940. vertexData.positions = positions;
  34941. vertexData.normals = normals;
  34942. vertexData.uvs = uvs;
  34943. if (faceColors) {
  34944. vertexData.colors = colors;
  34945. }
  34946. return vertexData;
  34947. };
  34948. /**
  34949. * Creates the VertexData of the Torus.
  34950. */
  34951. VertexData.CreateTorus = function (options) {
  34952. var indices = [];
  34953. var positions = [];
  34954. var normals = [];
  34955. var uvs = [];
  34956. var diameter = options.diameter || 1;
  34957. var thickness = options.thickness || 0.5;
  34958. var tessellation = options.tessellation || 16;
  34959. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34960. var stride = tessellation + 1;
  34961. for (var i = 0; i <= tessellation; i++) {
  34962. var u = i / tessellation;
  34963. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34964. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34965. for (var j = 0; j <= tessellation; j++) {
  34966. var v = 1 - j / tessellation;
  34967. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34968. var dx = Math.cos(innerAngle);
  34969. var dy = Math.sin(innerAngle);
  34970. // Create a vertex.
  34971. var normal = new BABYLON.Vector3(dx, dy, 0);
  34972. var position = normal.scale(thickness / 2);
  34973. var textureCoordinate = new BABYLON.Vector2(u, v);
  34974. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34975. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34976. positions.push(position.x, position.y, position.z);
  34977. normals.push(normal.x, normal.y, normal.z);
  34978. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34979. // And create indices for two triangles.
  34980. var nextI = (i + 1) % stride;
  34981. var nextJ = (j + 1) % stride;
  34982. indices.push(i * stride + j);
  34983. indices.push(i * stride + nextJ);
  34984. indices.push(nextI * stride + j);
  34985. indices.push(i * stride + nextJ);
  34986. indices.push(nextI * stride + nextJ);
  34987. indices.push(nextI * stride + j);
  34988. }
  34989. }
  34990. // Sides
  34991. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34992. // Result
  34993. var vertexData = new VertexData();
  34994. vertexData.indices = indices;
  34995. vertexData.positions = positions;
  34996. vertexData.normals = normals;
  34997. vertexData.uvs = uvs;
  34998. return vertexData;
  34999. };
  35000. /**
  35001. * Creates the VertexData of the LineSystem.
  35002. */
  35003. VertexData.CreateLineSystem = function (options) {
  35004. var indices = [];
  35005. var positions = [];
  35006. var lines = options.lines;
  35007. var colors = options.colors;
  35008. var vertexColors = [];
  35009. var idx = 0;
  35010. for (var l = 0; l < lines.length; l++) {
  35011. var points = lines[l];
  35012. for (var index = 0; index < points.length; index++) {
  35013. positions.push(points[index].x, points[index].y, points[index].z);
  35014. if (colors) {
  35015. var color = colors[l];
  35016. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  35017. }
  35018. if (index > 0) {
  35019. indices.push(idx - 1);
  35020. indices.push(idx);
  35021. }
  35022. idx++;
  35023. }
  35024. }
  35025. var vertexData = new VertexData();
  35026. vertexData.indices = indices;
  35027. vertexData.positions = positions;
  35028. if (colors) {
  35029. vertexData.colors = vertexColors;
  35030. }
  35031. return vertexData;
  35032. };
  35033. /**
  35034. * Create the VertexData of the DashedLines.
  35035. */
  35036. VertexData.CreateDashedLines = function (options) {
  35037. var dashSize = options.dashSize || 3;
  35038. var gapSize = options.gapSize || 1;
  35039. var dashNb = options.dashNb || 200;
  35040. var points = options.points;
  35041. var positions = new Array();
  35042. var indices = new Array();
  35043. var curvect = BABYLON.Vector3.Zero();
  35044. var lg = 0;
  35045. var nb = 0;
  35046. var shft = 0;
  35047. var dashshft = 0;
  35048. var curshft = 0;
  35049. var idx = 0;
  35050. var i = 0;
  35051. for (i = 0; i < points.length - 1; i++) {
  35052. points[i + 1].subtractToRef(points[i], curvect);
  35053. lg += curvect.length();
  35054. }
  35055. shft = lg / dashNb;
  35056. dashshft = dashSize * shft / (dashSize + gapSize);
  35057. for (i = 0; i < points.length - 1; i++) {
  35058. points[i + 1].subtractToRef(points[i], curvect);
  35059. nb = Math.floor(curvect.length() / shft);
  35060. curvect.normalize();
  35061. for (var j = 0; j < nb; j++) {
  35062. curshft = shft * j;
  35063. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  35064. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  35065. indices.push(idx, idx + 1);
  35066. idx += 2;
  35067. }
  35068. }
  35069. // Result
  35070. var vertexData = new VertexData();
  35071. vertexData.positions = positions;
  35072. vertexData.indices = indices;
  35073. return vertexData;
  35074. };
  35075. /**
  35076. * Creates the VertexData of the Ground.
  35077. */
  35078. VertexData.CreateGround = function (options) {
  35079. var indices = [];
  35080. var positions = [];
  35081. var normals = [];
  35082. var uvs = [];
  35083. var row, col;
  35084. var width = options.width || 1;
  35085. var height = options.height || 1;
  35086. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  35087. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  35088. for (row = 0; row <= subdivisionsY; row++) {
  35089. for (col = 0; col <= subdivisionsX; col++) {
  35090. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  35091. var normal = new BABYLON.Vector3(0, 1.0, 0);
  35092. positions.push(position.x, position.y, position.z);
  35093. normals.push(normal.x, normal.y, normal.z);
  35094. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  35095. }
  35096. }
  35097. for (row = 0; row < subdivisionsY; row++) {
  35098. for (col = 0; col < subdivisionsX; col++) {
  35099. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  35100. indices.push(col + 1 + row * (subdivisionsX + 1));
  35101. indices.push(col + row * (subdivisionsX + 1));
  35102. indices.push(col + (row + 1) * (subdivisionsX + 1));
  35103. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  35104. indices.push(col + row * (subdivisionsX + 1));
  35105. }
  35106. }
  35107. // Result
  35108. var vertexData = new VertexData();
  35109. vertexData.indices = indices;
  35110. vertexData.positions = positions;
  35111. vertexData.normals = normals;
  35112. vertexData.uvs = uvs;
  35113. return vertexData;
  35114. };
  35115. /**
  35116. * Creates the VertexData of the TiledGround.
  35117. */
  35118. VertexData.CreateTiledGround = function (options) {
  35119. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  35120. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  35121. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  35122. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  35123. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  35124. var precision = options.precision || { w: 1, h: 1 };
  35125. var indices = new Array();
  35126. var positions = new Array();
  35127. var normals = new Array();
  35128. var uvs = new Array();
  35129. var row, col, tileRow, tileCol;
  35130. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  35131. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  35132. precision.w = (precision.w < 1) ? 1 : precision.w;
  35133. precision.h = (precision.h < 1) ? 1 : precision.h;
  35134. var tileSize = {
  35135. 'w': (xmax - xmin) / subdivisions.w,
  35136. 'h': (zmax - zmin) / subdivisions.h
  35137. };
  35138. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  35139. // Indices
  35140. var base = positions.length / 3;
  35141. var rowLength = precision.w + 1;
  35142. for (row = 0; row < precision.h; row++) {
  35143. for (col = 0; col < precision.w; col++) {
  35144. var square = [
  35145. base + col + row * rowLength,
  35146. base + (col + 1) + row * rowLength,
  35147. base + (col + 1) + (row + 1) * rowLength,
  35148. base + col + (row + 1) * rowLength
  35149. ];
  35150. indices.push(square[1]);
  35151. indices.push(square[2]);
  35152. indices.push(square[3]);
  35153. indices.push(square[0]);
  35154. indices.push(square[1]);
  35155. indices.push(square[3]);
  35156. }
  35157. }
  35158. // Position, normals and uvs
  35159. var position = BABYLON.Vector3.Zero();
  35160. var normal = new BABYLON.Vector3(0, 1.0, 0);
  35161. for (row = 0; row <= precision.h; row++) {
  35162. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  35163. for (col = 0; col <= precision.w; col++) {
  35164. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  35165. position.y = 0;
  35166. positions.push(position.x, position.y, position.z);
  35167. normals.push(normal.x, normal.y, normal.z);
  35168. uvs.push(col / precision.w, row / precision.h);
  35169. }
  35170. }
  35171. }
  35172. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  35173. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  35174. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  35175. }
  35176. }
  35177. // Result
  35178. var vertexData = new VertexData();
  35179. vertexData.indices = indices;
  35180. vertexData.positions = positions;
  35181. vertexData.normals = normals;
  35182. vertexData.uvs = uvs;
  35183. return vertexData;
  35184. };
  35185. /**
  35186. * Creates the VertexData of the Ground designed from a heightmap.
  35187. */
  35188. VertexData.CreateGroundFromHeightMap = function (options) {
  35189. var indices = [];
  35190. var positions = [];
  35191. var normals = [];
  35192. var uvs = [];
  35193. var row, col;
  35194. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  35195. // Vertices
  35196. for (row = 0; row <= options.subdivisions; row++) {
  35197. for (col = 0; col <= options.subdivisions; col++) {
  35198. 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));
  35199. // Compute height
  35200. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  35201. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  35202. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  35203. var r = options.buffer[pos] / 255.0;
  35204. var g = options.buffer[pos + 1] / 255.0;
  35205. var b = options.buffer[pos + 2] / 255.0;
  35206. var gradient = r * filter.r + g * filter.g + b * filter.b;
  35207. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  35208. // Add vertex
  35209. positions.push(position.x, position.y, position.z);
  35210. normals.push(0, 0, 0);
  35211. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  35212. }
  35213. }
  35214. // Indices
  35215. for (row = 0; row < options.subdivisions; row++) {
  35216. for (col = 0; col < options.subdivisions; col++) {
  35217. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  35218. indices.push(col + 1 + row * (options.subdivisions + 1));
  35219. indices.push(col + row * (options.subdivisions + 1));
  35220. indices.push(col + (row + 1) * (options.subdivisions + 1));
  35221. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  35222. indices.push(col + row * (options.subdivisions + 1));
  35223. }
  35224. }
  35225. // Normals
  35226. VertexData.ComputeNormals(positions, indices, normals);
  35227. // Result
  35228. var vertexData = new VertexData();
  35229. vertexData.indices = indices;
  35230. vertexData.positions = positions;
  35231. vertexData.normals = normals;
  35232. vertexData.uvs = uvs;
  35233. return vertexData;
  35234. };
  35235. /**
  35236. * Creates the VertexData of the Plane.
  35237. */
  35238. VertexData.CreatePlane = function (options) {
  35239. var indices = [];
  35240. var positions = [];
  35241. var normals = [];
  35242. var uvs = [];
  35243. var width = options.width || options.size || 1;
  35244. var height = options.height || options.size || 1;
  35245. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35246. // Vertices
  35247. var halfWidth = width / 2.0;
  35248. var halfHeight = height / 2.0;
  35249. positions.push(-halfWidth, -halfHeight, 0);
  35250. normals.push(0, 0, -1.0);
  35251. uvs.push(0.0, 0.0);
  35252. positions.push(halfWidth, -halfHeight, 0);
  35253. normals.push(0, 0, -1.0);
  35254. uvs.push(1.0, 0.0);
  35255. positions.push(halfWidth, halfHeight, 0);
  35256. normals.push(0, 0, -1.0);
  35257. uvs.push(1.0, 1.0);
  35258. positions.push(-halfWidth, halfHeight, 0);
  35259. normals.push(0, 0, -1.0);
  35260. uvs.push(0.0, 1.0);
  35261. // Indices
  35262. indices.push(0);
  35263. indices.push(1);
  35264. indices.push(2);
  35265. indices.push(0);
  35266. indices.push(2);
  35267. indices.push(3);
  35268. // Sides
  35269. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35270. // Result
  35271. var vertexData = new VertexData();
  35272. vertexData.indices = indices;
  35273. vertexData.positions = positions;
  35274. vertexData.normals = normals;
  35275. vertexData.uvs = uvs;
  35276. return vertexData;
  35277. };
  35278. /**
  35279. * Creates the VertexData of the Disc or regular Polygon.
  35280. */
  35281. VertexData.CreateDisc = function (options) {
  35282. var positions = new Array();
  35283. var indices = new Array();
  35284. var normals = new Array();
  35285. var uvs = new Array();
  35286. var radius = options.radius || 0.5;
  35287. var tessellation = options.tessellation || 64;
  35288. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  35289. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35290. // positions and uvs
  35291. positions.push(0, 0, 0); // disc center first
  35292. uvs.push(0.5, 0.5);
  35293. var theta = Math.PI * 2 * arc;
  35294. var step = theta / tessellation;
  35295. for (var a = 0; a < theta; a += step) {
  35296. var x = Math.cos(a);
  35297. var y = Math.sin(a);
  35298. var u = (x + 1) / 2;
  35299. var v = (1 - y) / 2;
  35300. positions.push(radius * x, radius * y, 0);
  35301. uvs.push(u, v);
  35302. }
  35303. if (arc === 1) {
  35304. positions.push(positions[3], positions[4], positions[5]); // close the circle
  35305. uvs.push(uvs[2], uvs[3]);
  35306. }
  35307. //indices
  35308. var vertexNb = positions.length / 3;
  35309. for (var i = 1; i < vertexNb - 1; i++) {
  35310. indices.push(i + 1, 0, i);
  35311. }
  35312. // result
  35313. VertexData.ComputeNormals(positions, indices, normals);
  35314. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35315. var vertexData = new VertexData();
  35316. vertexData.indices = indices;
  35317. vertexData.positions = positions;
  35318. vertexData.normals = normals;
  35319. vertexData.uvs = uvs;
  35320. return vertexData;
  35321. };
  35322. /**
  35323. * Re-creates the VertexData of the Polygon for sideOrientation.
  35324. */
  35325. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  35326. var faceUV = fUV || new Array(3);
  35327. var faceColors = fColors;
  35328. var colors = [];
  35329. // default face colors and UV if undefined
  35330. for (var f = 0; f < 3; f++) {
  35331. if (faceUV[f] === undefined) {
  35332. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35333. }
  35334. if (faceColors && faceColors[f] === undefined) {
  35335. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35336. }
  35337. }
  35338. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35339. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35340. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35341. var indices = polygon.getIndices();
  35342. // set face colours and textures
  35343. var idx = 0;
  35344. var face = 0;
  35345. for (var index = 0; index < normals.length; index += 3) {
  35346. //Edge Face no. 1
  35347. if (Math.abs(normals[index + 1]) < 0.001) {
  35348. face = 1;
  35349. }
  35350. //Top Face no. 0
  35351. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  35352. face = 0;
  35353. }
  35354. //Bottom Face no. 2
  35355. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  35356. face = 2;
  35357. }
  35358. idx = index / 3;
  35359. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  35360. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  35361. if (faceColors) {
  35362. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  35363. }
  35364. }
  35365. // sides
  35366. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  35367. // Result
  35368. var vertexData = new VertexData();
  35369. vertexData.indices = indices;
  35370. vertexData.positions = positions;
  35371. vertexData.normals = normals;
  35372. vertexData.uvs = uvs;
  35373. if (faceColors) {
  35374. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  35375. vertexData.colors = totalColors;
  35376. }
  35377. return vertexData;
  35378. };
  35379. /**
  35380. * Creates the VertexData of the IcoSphere.
  35381. */
  35382. VertexData.CreateIcoSphere = function (options) {
  35383. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35384. var radius = options.radius || 1;
  35385. var flat = (options.flat === undefined) ? true : options.flat;
  35386. var subdivisions = options.subdivisions || 4;
  35387. var radiusX = options.radiusX || radius;
  35388. var radiusY = options.radiusY || radius;
  35389. var radiusZ = options.radiusZ || radius;
  35390. var t = (1 + Math.sqrt(5)) / 2;
  35391. // 12 vertex x,y,z
  35392. var ico_vertices = [
  35393. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  35394. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  35395. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  35396. ];
  35397. // index of 3 vertex makes a face of icopshere
  35398. var ico_indices = [
  35399. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  35400. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  35401. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  35402. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  35403. ];
  35404. // vertex for uv have aliased position, not for UV
  35405. var vertices_unalias_id = [
  35406. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  35407. // vertex alias
  35408. 0,
  35409. 2,
  35410. 3,
  35411. 3,
  35412. 3,
  35413. 4,
  35414. 7,
  35415. 8,
  35416. 9,
  35417. 9,
  35418. 10,
  35419. 11 // 23: B + 12
  35420. ];
  35421. // uv as integer step (not pixels !)
  35422. var ico_vertexuv = [
  35423. 5, 1, 3, 1, 6, 4, 0, 0,
  35424. 5, 3, 4, 2, 2, 2, 4, 0,
  35425. 2, 0, 1, 1, 6, 0, 6, 2,
  35426. // vertex alias (for same vertex on different faces)
  35427. 0, 4,
  35428. 3, 3,
  35429. 4, 4,
  35430. 3, 1,
  35431. 4, 2,
  35432. 4, 4,
  35433. 0, 2,
  35434. 1, 1,
  35435. 2, 2,
  35436. 3, 3,
  35437. 1, 3,
  35438. 2, 4 // 23: B + 12
  35439. ];
  35440. // Vertices[0, 1, ...9, A, B] : position on UV plane
  35441. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  35442. // First island of uv mapping
  35443. // v = 4h 3+ 2
  35444. // v = 3h 9+ 4
  35445. // v = 2h 9+ 5 B
  35446. // v = 1h 9 1 0
  35447. // v = 0h 3 8 7 A
  35448. // u = 0 1 2 3 4 5 6 *a
  35449. // Second island of uv mapping
  35450. // v = 4h 0+ B+ 4+
  35451. // v = 3h A+ 2+
  35452. // v = 2h 7+ 6 3+
  35453. // v = 1h 8+ 3+
  35454. // v = 0h
  35455. // u = 0 1 2 3 4 5 6 *a
  35456. // Face layout on texture UV mapping
  35457. // ============
  35458. // \ 4 /\ 16 / ======
  35459. // \ / \ / /\ 11 /
  35460. // \/ 7 \/ / \ /
  35461. // ======= / 10 \/
  35462. // /\ 17 /\ =======
  35463. // / \ / \ \ 15 /\
  35464. // / 8 \/ 12 \ \ / \
  35465. // ============ \/ 6 \
  35466. // \ 18 /\ ============
  35467. // \ / \ \ 5 /\ 0 /
  35468. // \/ 13 \ \ / \ /
  35469. // ======= \/ 1 \/
  35470. // =============
  35471. // /\ 19 /\ 2 /\
  35472. // / \ / \ / \
  35473. // / 14 \/ 9 \/ 3 \
  35474. // ===================
  35475. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  35476. var ustep = 138 / 1024;
  35477. var vstep = 239 / 1024;
  35478. var uoffset = 60 / 1024;
  35479. var voffset = 26 / 1024;
  35480. // Second island should have margin, not to touch the first island
  35481. // avoid any borderline artefact in pixel rounding
  35482. var island_u_offset = -40 / 1024;
  35483. var island_v_offset = +20 / 1024;
  35484. // face is either island 0 or 1 :
  35485. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  35486. var island = [
  35487. 0, 0, 0, 0, 1,
  35488. 0, 0, 1, 1, 0,
  35489. 0, 0, 1, 1, 0,
  35490. 0, 1, 1, 1, 0 // 15 - 19
  35491. ];
  35492. var indices = new Array();
  35493. var positions = new Array();
  35494. var normals = new Array();
  35495. var uvs = new Array();
  35496. var current_indice = 0;
  35497. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  35498. var face_vertex_pos = new Array(3);
  35499. var face_vertex_uv = new Array(3);
  35500. var v012;
  35501. for (v012 = 0; v012 < 3; v012++) {
  35502. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  35503. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  35504. }
  35505. // create all with normals
  35506. for (var face = 0; face < 20; face++) {
  35507. // 3 vertex per face
  35508. for (v012 = 0; v012 < 3; v012++) {
  35509. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  35510. var v_id = ico_indices[3 * face + v012];
  35511. // vertex have 3D position (x,y,z)
  35512. 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]);
  35513. // Normalize to get normal, then scale to radius
  35514. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  35515. // uv Coordinates from vertex ID
  35516. 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);
  35517. }
  35518. // Subdivide the face (interpolate pos, norm, uv)
  35519. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  35520. // - norm is linear interpolation of vertex corner normal
  35521. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  35522. // - uv is linear interpolation
  35523. //
  35524. // Topology is as below for sub-divide by 2
  35525. // vertex shown as v0,v1,v2
  35526. // interp index is i1 to progress in range [v0,v1[
  35527. // interp index is i2 to progress in range [v0,v2[
  35528. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  35529. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  35530. //
  35531. //
  35532. // i2 v2
  35533. // ^ ^
  35534. // / / \
  35535. // / / \
  35536. // / / \
  35537. // / / (0,1) \
  35538. // / #---------\
  35539. // / / \ (0,0)'/ \
  35540. // / / \ / \
  35541. // / / \ / \
  35542. // / / (0,0) \ / (1,0) \
  35543. // / #---------#---------\
  35544. // v0 v1
  35545. //
  35546. // --------------------> i1
  35547. //
  35548. // interp of (i1,i2):
  35549. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  35550. // along i1 : lerp(x0,x1, i1/(S-i2))
  35551. //
  35552. // centroid of triangle is needed to get help normal computation
  35553. // (c1,c2) are used for centroid location
  35554. var interp_vertex = function (i1, i2, c1, c2) {
  35555. // vertex is interpolated from
  35556. // - face_vertex_pos[0..2]
  35557. // - face_vertex_uv[0..2]
  35558. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  35559. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  35560. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  35561. pos_interp.normalize();
  35562. var vertex_normal;
  35563. if (flat) {
  35564. // in flat mode, recalculate normal as face centroid normal
  35565. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  35566. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  35567. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  35568. }
  35569. else {
  35570. // in smooth mode, recalculate normal from each single vertex position
  35571. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  35572. }
  35573. // Vertex normal need correction due to X,Y,Z radius scaling
  35574. vertex_normal.x /= radiusX;
  35575. vertex_normal.y /= radiusY;
  35576. vertex_normal.z /= radiusZ;
  35577. vertex_normal.normalize();
  35578. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  35579. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  35580. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  35581. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  35582. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  35583. uvs.push(uv_interp.x, uv_interp.y);
  35584. // push each vertex has member of a face
  35585. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  35586. indices.push(current_indice);
  35587. current_indice++;
  35588. };
  35589. for (var i2 = 0; i2 < subdivisions; i2++) {
  35590. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  35591. // face : (i1,i2) for /\ :
  35592. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  35593. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  35594. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  35595. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  35596. if (i1 + i2 + 1 < subdivisions) {
  35597. // face : (i1,i2)' for \/ :
  35598. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  35599. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  35600. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  35601. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  35602. }
  35603. }
  35604. }
  35605. }
  35606. // Sides
  35607. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35608. // Result
  35609. var vertexData = new VertexData();
  35610. vertexData.indices = indices;
  35611. vertexData.positions = positions;
  35612. vertexData.normals = normals;
  35613. vertexData.uvs = uvs;
  35614. return vertexData;
  35615. };
  35616. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  35617. /**
  35618. * Creates the VertexData of the Polyhedron.
  35619. */
  35620. VertexData.CreatePolyhedron = function (options) {
  35621. // provided polyhedron types :
  35622. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  35623. // 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)
  35624. var polyhedra = [];
  35625. 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]] };
  35626. 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]] };
  35627. polyhedra[2] = {
  35628. 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]],
  35629. 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]]
  35630. };
  35631. polyhedra[3] = {
  35632. 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]],
  35633. 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]]
  35634. };
  35635. polyhedra[4] = {
  35636. 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]],
  35637. 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]]
  35638. };
  35639. 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]] };
  35640. 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]] };
  35641. 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]] };
  35642. 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]] };
  35643. 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]] };
  35644. 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]] };
  35645. 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]] };
  35646. 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]] };
  35647. 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]] };
  35648. polyhedra[14] = {
  35649. 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]],
  35650. 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]]
  35651. };
  35652. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  35653. var size = options.size;
  35654. var sizeX = options.sizeX || size || 1;
  35655. var sizeY = options.sizeY || size || 1;
  35656. var sizeZ = options.sizeZ || size || 1;
  35657. var data = options.custom || polyhedra[type];
  35658. var nbfaces = data.face.length;
  35659. var faceUV = options.faceUV || new Array(nbfaces);
  35660. var faceColors = options.faceColors;
  35661. var flat = (options.flat === undefined) ? true : options.flat;
  35662. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35663. var positions = new Array();
  35664. var indices = new Array();
  35665. var normals = new Array();
  35666. var uvs = new Array();
  35667. var colors = new Array();
  35668. var index = 0;
  35669. var faceIdx = 0; // face cursor in the array "indexes"
  35670. var indexes = new Array();
  35671. var i = 0;
  35672. var f = 0;
  35673. var u, v, ang, x, y, tmp;
  35674. // default face colors and UV if undefined
  35675. if (flat) {
  35676. for (f = 0; f < nbfaces; f++) {
  35677. if (faceColors && faceColors[f] === undefined) {
  35678. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35679. }
  35680. if (faceUV && faceUV[f] === undefined) {
  35681. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35682. }
  35683. }
  35684. }
  35685. if (!flat) {
  35686. for (i = 0; i < data.vertex.length; i++) {
  35687. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  35688. uvs.push(0, 0);
  35689. }
  35690. for (f = 0; f < nbfaces; f++) {
  35691. for (i = 0; i < data.face[f].length - 2; i++) {
  35692. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  35693. }
  35694. }
  35695. }
  35696. else {
  35697. for (f = 0; f < nbfaces; f++) {
  35698. var fl = data.face[f].length; // number of vertices of the current face
  35699. ang = 2 * Math.PI / fl;
  35700. x = 0.5 * Math.tan(ang / 2);
  35701. y = 0.5;
  35702. // positions, uvs, colors
  35703. for (i = 0; i < fl; i++) {
  35704. // positions
  35705. 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);
  35706. indexes.push(index);
  35707. index++;
  35708. // uvs
  35709. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  35710. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  35711. uvs.push(u, v);
  35712. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  35713. y = x * Math.sin(ang) + y * Math.cos(ang);
  35714. x = tmp;
  35715. // colors
  35716. if (faceColors) {
  35717. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  35718. }
  35719. }
  35720. // indices from indexes
  35721. for (i = 0; i < fl - 2; i++) {
  35722. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  35723. }
  35724. faceIdx += fl;
  35725. }
  35726. }
  35727. VertexData.ComputeNormals(positions, indices, normals);
  35728. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35729. var vertexData = new VertexData();
  35730. vertexData.positions = positions;
  35731. vertexData.indices = indices;
  35732. vertexData.normals = normals;
  35733. vertexData.uvs = uvs;
  35734. if (faceColors && flat) {
  35735. vertexData.colors = colors;
  35736. }
  35737. return vertexData;
  35738. };
  35739. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  35740. /**
  35741. * Creates the VertexData of the Torus Knot.
  35742. */
  35743. VertexData.CreateTorusKnot = function (options) {
  35744. var indices = new Array();
  35745. var positions = new Array();
  35746. var normals = new Array();
  35747. var uvs = new Array();
  35748. var radius = options.radius || 2;
  35749. var tube = options.tube || 0.5;
  35750. var radialSegments = options.radialSegments || 32;
  35751. var tubularSegments = options.tubularSegments || 32;
  35752. var p = options.p || 2;
  35753. var q = options.q || 3;
  35754. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35755. // Helper
  35756. var getPos = function (angle) {
  35757. var cu = Math.cos(angle);
  35758. var su = Math.sin(angle);
  35759. var quOverP = q / p * angle;
  35760. var cs = Math.cos(quOverP);
  35761. var tx = radius * (2 + cs) * 0.5 * cu;
  35762. var ty = radius * (2 + cs) * su * 0.5;
  35763. var tz = radius * Math.sin(quOverP) * 0.5;
  35764. return new BABYLON.Vector3(tx, ty, tz);
  35765. };
  35766. // Vertices
  35767. var i;
  35768. var j;
  35769. for (i = 0; i <= radialSegments; i++) {
  35770. var modI = i % radialSegments;
  35771. var u = modI / radialSegments * 2 * p * Math.PI;
  35772. var p1 = getPos(u);
  35773. var p2 = getPos(u + 0.01);
  35774. var tang = p2.subtract(p1);
  35775. var n = p2.add(p1);
  35776. var bitan = BABYLON.Vector3.Cross(tang, n);
  35777. n = BABYLON.Vector3.Cross(bitan, tang);
  35778. bitan.normalize();
  35779. n.normalize();
  35780. for (j = 0; j < tubularSegments; j++) {
  35781. var modJ = j % tubularSegments;
  35782. var v = modJ / tubularSegments * 2 * Math.PI;
  35783. var cx = -tube * Math.cos(v);
  35784. var cy = tube * Math.sin(v);
  35785. positions.push(p1.x + cx * n.x + cy * bitan.x);
  35786. positions.push(p1.y + cx * n.y + cy * bitan.y);
  35787. positions.push(p1.z + cx * n.z + cy * bitan.z);
  35788. uvs.push(i / radialSegments);
  35789. uvs.push(j / tubularSegments);
  35790. }
  35791. }
  35792. for (i = 0; i < radialSegments; i++) {
  35793. for (j = 0; j < tubularSegments; j++) {
  35794. var jNext = (j + 1) % tubularSegments;
  35795. var a = i * tubularSegments + j;
  35796. var b = (i + 1) * tubularSegments + j;
  35797. var c = (i + 1) * tubularSegments + jNext;
  35798. var d = i * tubularSegments + jNext;
  35799. indices.push(d);
  35800. indices.push(b);
  35801. indices.push(a);
  35802. indices.push(d);
  35803. indices.push(c);
  35804. indices.push(b);
  35805. }
  35806. }
  35807. // Normals
  35808. VertexData.ComputeNormals(positions, indices, normals);
  35809. // Sides
  35810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35811. // Result
  35812. var vertexData = new VertexData();
  35813. vertexData.indices = indices;
  35814. vertexData.positions = positions;
  35815. vertexData.normals = normals;
  35816. vertexData.uvs = uvs;
  35817. return vertexData;
  35818. };
  35819. // Tools
  35820. /**
  35821. * @param {any} - positions (number[] or Float32Array)
  35822. * @param {any} - indices (number[] or Uint16Array)
  35823. * @param {any} - normals (number[] or Float32Array)
  35824. * options (optional) :
  35825. * facetPositions : optional array of facet positions (vector3)
  35826. * facetNormals : optional array of facet normals (vector3)
  35827. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  35828. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  35829. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  35830. * bbSize : optional bounding box size data, required for facetPartitioning computation
  35831. * bInfo : optional bounding info, required for facetPartitioning computation
  35832. * useRightHandedSystem: optional boolean to for right handed system computation
  35833. * depthSort : optional boolean to enable the facet depth sort computation
  35834. * distanceTo : optional Vector3 to compute the facet depth from this location
  35835. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  35836. */
  35837. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  35838. // temporary scalar variables
  35839. var index = 0; // facet index
  35840. var p1p2x = 0.0; // p1p2 vector x coordinate
  35841. var p1p2y = 0.0; // p1p2 vector y coordinate
  35842. var p1p2z = 0.0; // p1p2 vector z coordinate
  35843. var p3p2x = 0.0; // p3p2 vector x coordinate
  35844. var p3p2y = 0.0; // p3p2 vector y coordinate
  35845. var p3p2z = 0.0; // p3p2 vector z coordinate
  35846. var faceNormalx = 0.0; // facet normal x coordinate
  35847. var faceNormaly = 0.0; // facet normal y coordinate
  35848. var faceNormalz = 0.0; // facet normal z coordinate
  35849. var length = 0.0; // facet normal length before normalization
  35850. var v1x = 0; // vector1 x index in the positions array
  35851. var v1y = 0; // vector1 y index in the positions array
  35852. var v1z = 0; // vector1 z index in the positions array
  35853. var v2x = 0; // vector2 x index in the positions array
  35854. var v2y = 0; // vector2 y index in the positions array
  35855. var v2z = 0; // vector2 z index in the positions array
  35856. var v3x = 0; // vector3 x index in the positions array
  35857. var v3y = 0; // vector3 y index in the positions array
  35858. var v3z = 0; // vector3 z index in the positions array
  35859. var computeFacetNormals = false;
  35860. var computeFacetPositions = false;
  35861. var computeFacetPartitioning = false;
  35862. var computeDepthSort = false;
  35863. var faceNormalSign = 1;
  35864. var ratio = 0;
  35865. var distanceTo = null;
  35866. if (options) {
  35867. computeFacetNormals = (options.facetNormals) ? true : false;
  35868. computeFacetPositions = (options.facetPositions) ? true : false;
  35869. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  35870. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  35871. ratio = options.ratio || 0;
  35872. computeDepthSort = (options.depthSort) ? true : false;
  35873. distanceTo = (options.distanceTo);
  35874. if (computeDepthSort) {
  35875. if (distanceTo === undefined) {
  35876. distanceTo = BABYLON.Vector3.Zero();
  35877. }
  35878. var depthSortedFacets = options.depthSortedFacets;
  35879. }
  35880. }
  35881. // facetPartitioning reinit if needed
  35882. var xSubRatio = 0;
  35883. var ySubRatio = 0;
  35884. var zSubRatio = 0;
  35885. var subSq = 0;
  35886. if (computeFacetPartitioning && options && options.bbSize) {
  35887. var ox = 0; // X partitioning index for facet position
  35888. var oy = 0; // Y partinioning index for facet position
  35889. var oz = 0; // Z partinioning index for facet position
  35890. var b1x = 0; // X partitioning index for facet v1 vertex
  35891. var b1y = 0; // Y partitioning index for facet v1 vertex
  35892. var b1z = 0; // z partitioning index for facet v1 vertex
  35893. var b2x = 0; // X partitioning index for facet v2 vertex
  35894. var b2y = 0; // Y partitioning index for facet v2 vertex
  35895. var b2z = 0; // Z partitioning index for facet v2 vertex
  35896. var b3x = 0; // X partitioning index for facet v3 vertex
  35897. var b3y = 0; // Y partitioning index for facet v3 vertex
  35898. var b3z = 0; // Z partitioning index for facet v3 vertex
  35899. var block_idx_o = 0; // facet barycenter block index
  35900. var block_idx_v1 = 0; // v1 vertex block index
  35901. var block_idx_v2 = 0; // v2 vertex block index
  35902. var block_idx_v3 = 0; // v3 vertex block index
  35903. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  35904. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  35905. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  35906. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  35907. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  35908. subSq = options.subDiv.max * options.subDiv.max;
  35909. options.facetPartitioning.length = 0;
  35910. }
  35911. // reset the normals
  35912. for (index = 0; index < positions.length; index++) {
  35913. normals[index] = 0.0;
  35914. }
  35915. // Loop : 1 indice triplet = 1 facet
  35916. var nbFaces = (indices.length / 3) | 0;
  35917. for (index = 0; index < nbFaces; index++) {
  35918. // get the indexes of the coordinates of each vertex of the facet
  35919. v1x = indices[index * 3] * 3;
  35920. v1y = v1x + 1;
  35921. v1z = v1x + 2;
  35922. v2x = indices[index * 3 + 1] * 3;
  35923. v2y = v2x + 1;
  35924. v2z = v2x + 2;
  35925. v3x = indices[index * 3 + 2] * 3;
  35926. v3y = v3x + 1;
  35927. v3z = v3x + 2;
  35928. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  35929. p1p2y = positions[v1y] - positions[v2y];
  35930. p1p2z = positions[v1z] - positions[v2z];
  35931. p3p2x = positions[v3x] - positions[v2x];
  35932. p3p2y = positions[v3y] - positions[v2y];
  35933. p3p2z = positions[v3z] - positions[v2z];
  35934. // compute the face normal with the cross product
  35935. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  35936. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  35937. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  35938. // normalize this normal and store it in the array facetData
  35939. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35940. length = (length === 0) ? 1.0 : length;
  35941. faceNormalx /= length;
  35942. faceNormaly /= length;
  35943. faceNormalz /= length;
  35944. if (computeFacetNormals && options) {
  35945. options.facetNormals[index].x = faceNormalx;
  35946. options.facetNormals[index].y = faceNormaly;
  35947. options.facetNormals[index].z = faceNormalz;
  35948. }
  35949. if (computeFacetPositions && options) {
  35950. // compute and the facet barycenter coordinates in the array facetPositions
  35951. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  35952. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35953. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35954. }
  35955. if (computeFacetPartitioning && options) {
  35956. // store the facet indexes in arrays in the main facetPartitioning array :
  35957. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35958. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  35959. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  35960. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  35961. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35962. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35963. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35964. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35965. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35966. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35967. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35968. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35969. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35970. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35971. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35972. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35973. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35974. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35975. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35976. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35977. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35978. // push each facet index in each block containing the vertex
  35979. options.facetPartitioning[block_idx_v1].push(index);
  35980. if (block_idx_v2 != block_idx_v1) {
  35981. options.facetPartitioning[block_idx_v2].push(index);
  35982. }
  35983. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35984. options.facetPartitioning[block_idx_v3].push(index);
  35985. }
  35986. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35987. options.facetPartitioning[block_idx_o].push(index);
  35988. }
  35989. }
  35990. if (computeDepthSort && options && options.facetPositions) {
  35991. var dsf = depthSortedFacets[index];
  35992. dsf.ind = index * 3;
  35993. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35994. }
  35995. // compute the normals anyway
  35996. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35997. normals[v1y] += faceNormaly;
  35998. normals[v1z] += faceNormalz;
  35999. normals[v2x] += faceNormalx;
  36000. normals[v2y] += faceNormaly;
  36001. normals[v2z] += faceNormalz;
  36002. normals[v3x] += faceNormalx;
  36003. normals[v3y] += faceNormaly;
  36004. normals[v3z] += faceNormalz;
  36005. }
  36006. // last normalization of each normal
  36007. for (index = 0; index < normals.length / 3; index++) {
  36008. faceNormalx = normals[index * 3];
  36009. faceNormaly = normals[index * 3 + 1];
  36010. faceNormalz = normals[index * 3 + 2];
  36011. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  36012. length = (length === 0) ? 1.0 : length;
  36013. faceNormalx /= length;
  36014. faceNormaly /= length;
  36015. faceNormalz /= length;
  36016. normals[index * 3] = faceNormalx;
  36017. normals[index * 3 + 1] = faceNormaly;
  36018. normals[index * 3 + 2] = faceNormalz;
  36019. }
  36020. };
  36021. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  36022. var li = indices.length;
  36023. var ln = normals.length;
  36024. var i;
  36025. var n;
  36026. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36027. switch (sideOrientation) {
  36028. case BABYLON.Mesh.FRONTSIDE:
  36029. // nothing changed
  36030. break;
  36031. case BABYLON.Mesh.BACKSIDE:
  36032. var tmp;
  36033. // indices
  36034. for (i = 0; i < li; i += 3) {
  36035. tmp = indices[i];
  36036. indices[i] = indices[i + 2];
  36037. indices[i + 2] = tmp;
  36038. }
  36039. // normals
  36040. for (n = 0; n < ln; n++) {
  36041. normals[n] = -normals[n];
  36042. }
  36043. break;
  36044. case BABYLON.Mesh.DOUBLESIDE:
  36045. // positions
  36046. var lp = positions.length;
  36047. var l = lp / 3;
  36048. for (var p = 0; p < lp; p++) {
  36049. positions[lp + p] = positions[p];
  36050. }
  36051. // indices
  36052. for (i = 0; i < li; i += 3) {
  36053. indices[i + li] = indices[i + 2] + l;
  36054. indices[i + 1 + li] = indices[i + 1] + l;
  36055. indices[i + 2 + li] = indices[i] + l;
  36056. }
  36057. // normals
  36058. for (n = 0; n < ln; n++) {
  36059. normals[ln + n] = -normals[n];
  36060. }
  36061. // uvs
  36062. var lu = uvs.length;
  36063. var u = 0;
  36064. for (u = 0; u < lu; u++) {
  36065. uvs[u + lu] = uvs[u];
  36066. }
  36067. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  36068. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  36069. u = 0;
  36070. for (i = 0; i < lu / 2; i++) {
  36071. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  36072. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  36073. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  36074. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  36075. u += 2;
  36076. }
  36077. break;
  36078. }
  36079. };
  36080. /**
  36081. * Creates a new VertexData from the imported parameters.
  36082. */
  36083. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  36084. var vertexData = new VertexData();
  36085. // positions
  36086. var positions = parsedVertexData.positions;
  36087. if (positions) {
  36088. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  36089. }
  36090. // normals
  36091. var normals = parsedVertexData.normals;
  36092. if (normals) {
  36093. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  36094. }
  36095. // tangents
  36096. var tangents = parsedVertexData.tangents;
  36097. if (tangents) {
  36098. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  36099. }
  36100. // uvs
  36101. var uvs = parsedVertexData.uvs;
  36102. if (uvs) {
  36103. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  36104. }
  36105. // uv2s
  36106. var uv2s = parsedVertexData.uv2s;
  36107. if (uv2s) {
  36108. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  36109. }
  36110. // uv3s
  36111. var uv3s = parsedVertexData.uv3s;
  36112. if (uv3s) {
  36113. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  36114. }
  36115. // uv4s
  36116. var uv4s = parsedVertexData.uv4s;
  36117. if (uv4s) {
  36118. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  36119. }
  36120. // uv5s
  36121. var uv5s = parsedVertexData.uv5s;
  36122. if (uv5s) {
  36123. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  36124. }
  36125. // uv6s
  36126. var uv6s = parsedVertexData.uv6s;
  36127. if (uv6s) {
  36128. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  36129. }
  36130. // colors
  36131. var colors = parsedVertexData.colors;
  36132. if (colors) {
  36133. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  36134. }
  36135. // matricesIndices
  36136. var matricesIndices = parsedVertexData.matricesIndices;
  36137. if (matricesIndices) {
  36138. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  36139. }
  36140. // matricesWeights
  36141. var matricesWeights = parsedVertexData.matricesWeights;
  36142. if (matricesWeights) {
  36143. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  36144. }
  36145. // indices
  36146. var indices = parsedVertexData.indices;
  36147. if (indices) {
  36148. vertexData.indices = indices;
  36149. }
  36150. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  36151. };
  36152. return VertexData;
  36153. }());
  36154. BABYLON.VertexData = VertexData;
  36155. })(BABYLON || (BABYLON = {}));
  36156. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  36157. "use strict";
  36158. var BABYLON;
  36159. (function (BABYLON) {
  36160. /**
  36161. * Class used to store geometry data (vertex buffers + index buffer)
  36162. */
  36163. var Geometry = /** @class */ (function () {
  36164. /**
  36165. * Creates a new geometry
  36166. * @param id defines the unique ID
  36167. * @param scene defines the hosting scene
  36168. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  36169. * @param updatable defines if geometry must be updatable (false by default)
  36170. * @param mesh defines the mesh that will be associated with the geometry
  36171. */
  36172. function Geometry(id, scene, vertexData, updatable, mesh) {
  36173. if (updatable === void 0) { updatable = false; }
  36174. if (mesh === void 0) { mesh = null; }
  36175. /**
  36176. * Gets the delay loading state of the geometry (none by default which means not delayed)
  36177. */
  36178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36179. this._totalVertices = 0;
  36180. this._isDisposed = false;
  36181. this._indexBufferIsUpdatable = false;
  36182. this.id = id;
  36183. this._engine = scene.getEngine();
  36184. this._meshes = [];
  36185. this._scene = scene;
  36186. //Init vertex buffer cache
  36187. this._vertexBuffers = {};
  36188. this._indices = [];
  36189. this._updatable = updatable;
  36190. // vertexData
  36191. if (vertexData) {
  36192. this.setAllVerticesData(vertexData, updatable);
  36193. }
  36194. else {
  36195. this._totalVertices = 0;
  36196. this._indices = [];
  36197. }
  36198. if (this._engine.getCaps().vertexArrayObject) {
  36199. this._vertexArrayObjects = {};
  36200. }
  36201. // applyToMesh
  36202. if (mesh) {
  36203. if (mesh.getClassName() === "LinesMesh") {
  36204. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36205. this._updateExtend();
  36206. }
  36207. this.applyToMesh(mesh);
  36208. mesh.computeWorldMatrix(true);
  36209. }
  36210. }
  36211. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36212. /**
  36213. * 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
  36214. */
  36215. get: function () {
  36216. return this._boundingBias;
  36217. },
  36218. /**
  36219. * 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
  36220. */
  36221. set: function (value) {
  36222. if (this._boundingBias && this._boundingBias.equals(value)) {
  36223. return;
  36224. }
  36225. this._boundingBias = value.clone();
  36226. this._updateBoundingInfo(true, null);
  36227. },
  36228. enumerable: true,
  36229. configurable: true
  36230. });
  36231. /**
  36232. * Static function used to attach a new empty geometry to a mesh
  36233. * @param mesh defines the mesh to attach the geometry to
  36234. * @returns the new {BABYLON.Geometry}
  36235. */
  36236. Geometry.CreateGeometryForMesh = function (mesh) {
  36237. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  36238. geometry.applyToMesh(mesh);
  36239. return geometry;
  36240. };
  36241. Object.defineProperty(Geometry.prototype, "extend", {
  36242. /**
  36243. * Gets the current extend of the geometry
  36244. */
  36245. get: function () {
  36246. return this._extend;
  36247. },
  36248. enumerable: true,
  36249. configurable: true
  36250. });
  36251. /**
  36252. * Gets the hosting scene
  36253. * @returns the hosting {BABYLON.Scene}
  36254. */
  36255. Geometry.prototype.getScene = function () {
  36256. return this._scene;
  36257. };
  36258. /**
  36259. * Gets the hosting engine
  36260. * @returns the hosting {BABYLON.Engine}
  36261. */
  36262. Geometry.prototype.getEngine = function () {
  36263. return this._engine;
  36264. };
  36265. /**
  36266. * Defines if the geometry is ready to use
  36267. * @returns true if the geometry is ready to be used
  36268. */
  36269. Geometry.prototype.isReady = function () {
  36270. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36271. };
  36272. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36273. /**
  36274. * Gets a value indicating that the geometry should not be serialized
  36275. */
  36276. get: function () {
  36277. for (var index = 0; index < this._meshes.length; index++) {
  36278. if (!this._meshes[index].doNotSerialize) {
  36279. return false;
  36280. }
  36281. }
  36282. return true;
  36283. },
  36284. enumerable: true,
  36285. configurable: true
  36286. });
  36287. /** @ignore */
  36288. Geometry.prototype._rebuild = function () {
  36289. if (this._vertexArrayObjects) {
  36290. this._vertexArrayObjects = {};
  36291. }
  36292. // Index buffer
  36293. if (this._meshes.length !== 0 && this._indices) {
  36294. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36295. }
  36296. // Vertex buffers
  36297. for (var key in this._vertexBuffers) {
  36298. var vertexBuffer = this._vertexBuffers[key];
  36299. vertexBuffer._rebuild();
  36300. }
  36301. };
  36302. /**
  36303. * Affects all gemetry data in one call
  36304. * @param vertexData defines the geometry data
  36305. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  36306. */
  36307. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36308. vertexData.applyToGeometry(this, updatable);
  36309. this.notifyUpdate();
  36310. };
  36311. /**
  36312. * Set specific vertex data
  36313. * @param kind defines the data kind (Position, normal, etc...)
  36314. * @param data defines the vertex data to use
  36315. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  36316. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  36317. */
  36318. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36319. if (updatable === void 0) { updatable = false; }
  36320. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36321. this._totalVertices = data.length / (stride || 3);
  36322. }
  36323. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36324. this.setVerticesBuffer(buffer);
  36325. };
  36326. /**
  36327. * Removes a specific vertex data
  36328. * @param kind defines the data kind (Position, normal, etc...)
  36329. */
  36330. Geometry.prototype.removeVerticesData = function (kind) {
  36331. if (this._vertexBuffers[kind]) {
  36332. this._vertexBuffers[kind].dispose();
  36333. delete this._vertexBuffers[kind];
  36334. }
  36335. };
  36336. /**
  36337. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  36338. * @param buffer defines the vertex buffer to use
  36339. * @param totalVertices defines the total number of vertices for position kind (could be null)
  36340. */
  36341. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  36342. if (totalVertices === void 0) { totalVertices = null; }
  36343. var kind = buffer.getKind();
  36344. if (this._vertexBuffers[kind]) {
  36345. this._vertexBuffers[kind].dispose();
  36346. }
  36347. this._vertexBuffers[kind] = buffer;
  36348. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36349. if (totalVertices != null) {
  36350. this._totalVertices = totalVertices;
  36351. }
  36352. this._updateExtend();
  36353. this._resetPointsArrayCache();
  36354. var meshes = this._meshes;
  36355. var numOfMeshes = meshes.length;
  36356. for (var index = 0; index < numOfMeshes; index++) {
  36357. var mesh = meshes[index];
  36358. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36359. mesh._createGlobalSubMesh(false);
  36360. mesh.computeWorldMatrix(true);
  36361. }
  36362. }
  36363. this.notifyUpdate(kind);
  36364. if (this._vertexArrayObjects) {
  36365. this._disposeVertexArrayObjects();
  36366. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  36367. }
  36368. };
  36369. /**
  36370. * Update a specific vertex buffer
  36371. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  36372. * It will do nothing if the buffer is not updatable
  36373. * @param kind defines the data kind (Position, normal, etc...)
  36374. * @param data defines the data to use
  36375. * @param offset defines the offset in the target buffer where to store the data
  36376. */
  36377. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36378. var vertexBuffer = this.getVertexBuffer(kind);
  36379. if (!vertexBuffer) {
  36380. return;
  36381. }
  36382. vertexBuffer.updateDirectly(data, offset);
  36383. this.notifyUpdate(kind);
  36384. };
  36385. /**
  36386. * Update a specific vertex buffer
  36387. * This function will create a new buffer if the current one is not updatable
  36388. * @param kind defines the data kind (Position, normal, etc...)
  36389. * @param data defines the data to use
  36390. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  36391. */
  36392. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36393. if (updateExtends === void 0) { updateExtends = false; }
  36394. var vertexBuffer = this.getVertexBuffer(kind);
  36395. if (!vertexBuffer) {
  36396. return;
  36397. }
  36398. vertexBuffer.update(data);
  36399. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36400. this._updateBoundingInfo(updateExtends, data);
  36401. }
  36402. this.notifyUpdate(kind);
  36403. };
  36404. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  36405. if (updateExtends) {
  36406. this._updateExtend(data);
  36407. }
  36408. var meshes = this._meshes;
  36409. var numOfMeshes = meshes.length;
  36410. this._resetPointsArrayCache();
  36411. for (var index = 0; index < numOfMeshes; index++) {
  36412. var mesh = meshes[index];
  36413. if (updateExtends) {
  36414. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36415. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36416. var subMesh = mesh.subMeshes[subIndex];
  36417. subMesh.refreshBoundingInfo();
  36418. }
  36419. }
  36420. }
  36421. };
  36422. /** @ignore */
  36423. Geometry.prototype._bind = function (effect, indexToBind) {
  36424. if (!effect) {
  36425. return;
  36426. }
  36427. if (indexToBind === undefined) {
  36428. indexToBind = this._indexBuffer;
  36429. }
  36430. var vbs = this.getVertexBuffers();
  36431. if (!vbs) {
  36432. return;
  36433. }
  36434. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  36435. this._engine.bindBuffers(vbs, indexToBind, effect);
  36436. return;
  36437. }
  36438. // Using VAO
  36439. if (!this._vertexArrayObjects[effect.key]) {
  36440. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  36441. }
  36442. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  36443. };
  36444. /**
  36445. * Gets total number of vertices
  36446. * @returns the total number of vertices
  36447. */
  36448. Geometry.prototype.getTotalVertices = function () {
  36449. if (!this.isReady()) {
  36450. return 0;
  36451. }
  36452. return this._totalVertices;
  36453. };
  36454. /**
  36455. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  36456. * @param kind defines the data kind (Position, normal, etc...)
  36457. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  36458. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  36459. * @returns a float array containing vertex data
  36460. */
  36461. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  36462. var vertexBuffer = this.getVertexBuffer(kind);
  36463. if (!vertexBuffer) {
  36464. return null;
  36465. }
  36466. var data = vertexBuffer.getData();
  36467. if (!data) {
  36468. return null;
  36469. }
  36470. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  36471. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  36472. var count = this._totalVertices * defaultStride;
  36473. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  36474. var copy_1 = new Array(count);
  36475. vertexBuffer.forEach(count, function (value, index) {
  36476. copy_1[index] = value;
  36477. });
  36478. return copy_1;
  36479. }
  36480. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  36481. if (data instanceof Array) {
  36482. var offset = vertexBuffer.byteOffset / 4;
  36483. return BABYLON.Tools.Slice(data, offset, offset + count);
  36484. }
  36485. else if (data instanceof ArrayBuffer) {
  36486. return new Float32Array(data, vertexBuffer.byteOffset, count);
  36487. }
  36488. else {
  36489. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  36490. }
  36491. }
  36492. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  36493. return BABYLON.Tools.Slice(data);
  36494. }
  36495. return data;
  36496. };
  36497. /**
  36498. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  36499. * @param kind defines the data kind (Position, normal, etc...)
  36500. * @returns true if the vertex buffer with the specified kind is updatable
  36501. */
  36502. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  36503. var vb = this._vertexBuffers[kind];
  36504. if (!vb) {
  36505. return false;
  36506. }
  36507. return vb.isUpdatable();
  36508. };
  36509. /**
  36510. * Gets a specific vertex buffer
  36511. * @param kind defines the data kind (Position, normal, etc...)
  36512. * @returns a {BABYLON.VertexBuffer}
  36513. */
  36514. Geometry.prototype.getVertexBuffer = function (kind) {
  36515. if (!this.isReady()) {
  36516. return null;
  36517. }
  36518. return this._vertexBuffers[kind];
  36519. };
  36520. /**
  36521. * Returns all vertex buffers
  36522. * @return an object holding all vertex buffers indexed by kind
  36523. */
  36524. Geometry.prototype.getVertexBuffers = function () {
  36525. if (!this.isReady()) {
  36526. return null;
  36527. }
  36528. return this._vertexBuffers;
  36529. };
  36530. /**
  36531. * Gets a boolean indicating if specific vertex buffer is present
  36532. * @param kind defines the data kind (Position, normal, etc...)
  36533. * @returns true if data is present
  36534. */
  36535. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36536. if (!this._vertexBuffers) {
  36537. if (this._delayInfo) {
  36538. return this._delayInfo.indexOf(kind) !== -1;
  36539. }
  36540. return false;
  36541. }
  36542. return this._vertexBuffers[kind] !== undefined;
  36543. };
  36544. /**
  36545. * Gets a list of all attached data kinds (Position, normal, etc...)
  36546. * @returns a list of string containing all kinds
  36547. */
  36548. Geometry.prototype.getVerticesDataKinds = function () {
  36549. var result = [];
  36550. var kind;
  36551. if (!this._vertexBuffers && this._delayInfo) {
  36552. for (kind in this._delayInfo) {
  36553. result.push(kind);
  36554. }
  36555. }
  36556. else {
  36557. for (kind in this._vertexBuffers) {
  36558. result.push(kind);
  36559. }
  36560. }
  36561. return result;
  36562. };
  36563. /**
  36564. * Update index buffer
  36565. * @param indices defines the indices to store in the index buffer
  36566. * @param offset defines the offset in the target buffer where to store the data
  36567. */
  36568. Geometry.prototype.updateIndices = function (indices, offset) {
  36569. if (!this._indexBuffer) {
  36570. return;
  36571. }
  36572. if (!this._indexBufferIsUpdatable) {
  36573. this.setIndices(indices, null, true);
  36574. }
  36575. else {
  36576. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  36577. }
  36578. };
  36579. /**
  36580. * Creates a new index buffer
  36581. * @param indices defines the indices to store in the index buffer
  36582. * @param totalVertices defines the total number of vertices (could be null)
  36583. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  36584. */
  36585. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  36586. if (totalVertices === void 0) { totalVertices = null; }
  36587. if (updatable === void 0) { updatable = false; }
  36588. if (this._indexBuffer) {
  36589. this._engine._releaseBuffer(this._indexBuffer);
  36590. }
  36591. this._disposeVertexArrayObjects();
  36592. this._indices = indices;
  36593. this._indexBufferIsUpdatable = updatable;
  36594. if (this._meshes.length !== 0 && this._indices) {
  36595. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  36596. }
  36597. if (totalVertices != undefined) {
  36598. this._totalVertices = totalVertices;
  36599. }
  36600. var meshes = this._meshes;
  36601. var numOfMeshes = meshes.length;
  36602. for (var index = 0; index < numOfMeshes; index++) {
  36603. meshes[index]._createGlobalSubMesh(true);
  36604. }
  36605. this.notifyUpdate();
  36606. };
  36607. /**
  36608. * Return the total number of indices
  36609. * @returns the total number of indices
  36610. */
  36611. Geometry.prototype.getTotalIndices = function () {
  36612. if (!this.isReady()) {
  36613. return 0;
  36614. }
  36615. return this._indices.length;
  36616. };
  36617. /**
  36618. * Gets the index buffer array
  36619. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  36620. * @returns the index buffer array
  36621. */
  36622. Geometry.prototype.getIndices = function (copyWhenShared) {
  36623. if (!this.isReady()) {
  36624. return null;
  36625. }
  36626. var orig = this._indices;
  36627. if (!copyWhenShared || this._meshes.length === 1) {
  36628. return orig;
  36629. }
  36630. else {
  36631. var len = orig.length;
  36632. var copy = [];
  36633. for (var i = 0; i < len; i++) {
  36634. copy.push(orig[i]);
  36635. }
  36636. return copy;
  36637. }
  36638. };
  36639. /**
  36640. * Gets the index buffer
  36641. * @return the index buffer
  36642. */
  36643. Geometry.prototype.getIndexBuffer = function () {
  36644. if (!this.isReady()) {
  36645. return null;
  36646. }
  36647. return this._indexBuffer;
  36648. };
  36649. /** @ignore */
  36650. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  36651. if (effect === void 0) { effect = null; }
  36652. if (!effect || !this._vertexArrayObjects) {
  36653. return;
  36654. }
  36655. if (this._vertexArrayObjects[effect.key]) {
  36656. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  36657. delete this._vertexArrayObjects[effect.key];
  36658. }
  36659. };
  36660. /**
  36661. * Release the associated resources for a specific mesh
  36662. * @param mesh defines the source mesh
  36663. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  36664. */
  36665. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36666. var meshes = this._meshes;
  36667. var index = meshes.indexOf(mesh);
  36668. if (index === -1) {
  36669. return;
  36670. }
  36671. meshes.splice(index, 1);
  36672. mesh._geometry = null;
  36673. if (meshes.length === 0 && shouldDispose) {
  36674. this.dispose();
  36675. }
  36676. };
  36677. /**
  36678. * Apply current geometry to a given mesh
  36679. * @param mesh defines the mesh to apply geometry to
  36680. */
  36681. Geometry.prototype.applyToMesh = function (mesh) {
  36682. if (mesh._geometry === this) {
  36683. return;
  36684. }
  36685. var previousGeometry = mesh._geometry;
  36686. if (previousGeometry) {
  36687. previousGeometry.releaseForMesh(mesh);
  36688. }
  36689. var meshes = this._meshes;
  36690. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36691. mesh._geometry = this;
  36692. this._scene.pushGeometry(this);
  36693. meshes.push(mesh);
  36694. if (this.isReady()) {
  36695. this._applyToMesh(mesh);
  36696. }
  36697. else {
  36698. mesh._boundingInfo = this._boundingInfo;
  36699. }
  36700. };
  36701. Geometry.prototype._updateExtend = function (data) {
  36702. if (data === void 0) { data = null; }
  36703. if (!data) {
  36704. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36705. }
  36706. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  36707. };
  36708. Geometry.prototype._applyToMesh = function (mesh) {
  36709. var numOfMeshes = this._meshes.length;
  36710. // vertexBuffers
  36711. for (var kind in this._vertexBuffers) {
  36712. if (numOfMeshes === 1) {
  36713. this._vertexBuffers[kind].create();
  36714. }
  36715. var buffer = this._vertexBuffers[kind].getBuffer();
  36716. if (buffer)
  36717. buffer.references = numOfMeshes;
  36718. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36719. if (!this._extend) {
  36720. this._updateExtend();
  36721. }
  36722. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36723. mesh._createGlobalSubMesh(false);
  36724. //bounding info was just created again, world matrix should be applied again.
  36725. mesh._updateBoundingInfo();
  36726. }
  36727. }
  36728. // indexBuffer
  36729. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36730. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36731. }
  36732. if (this._indexBuffer) {
  36733. this._indexBuffer.references = numOfMeshes;
  36734. }
  36735. };
  36736. Geometry.prototype.notifyUpdate = function (kind) {
  36737. if (this.onGeometryUpdated) {
  36738. this.onGeometryUpdated(this, kind);
  36739. }
  36740. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  36741. var mesh = _a[_i];
  36742. mesh._markSubMeshesAsAttributesDirty();
  36743. }
  36744. };
  36745. /**
  36746. * Load the geometry if it was flagged as delay loaded
  36747. * @param scene defines the hosting scene
  36748. * @param onLoaded defines a callback called when the geometry is loaded
  36749. */
  36750. Geometry.prototype.load = function (scene, onLoaded) {
  36751. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36752. return;
  36753. }
  36754. if (this.isReady()) {
  36755. if (onLoaded) {
  36756. onLoaded();
  36757. }
  36758. return;
  36759. }
  36760. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36761. this._queueLoad(scene, onLoaded);
  36762. };
  36763. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36764. var _this = this;
  36765. if (!this.delayLoadingFile) {
  36766. return;
  36767. }
  36768. scene._addPendingData(this);
  36769. scene._loadFile(this.delayLoadingFile, function (data) {
  36770. if (!_this._delayLoadingFunction) {
  36771. return;
  36772. }
  36773. _this._delayLoadingFunction(JSON.parse(data), _this);
  36774. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36775. _this._delayInfo = [];
  36776. scene._removePendingData(_this);
  36777. var meshes = _this._meshes;
  36778. var numOfMeshes = meshes.length;
  36779. for (var index = 0; index < numOfMeshes; index++) {
  36780. _this._applyToMesh(meshes[index]);
  36781. }
  36782. if (onLoaded) {
  36783. onLoaded();
  36784. }
  36785. }, undefined, true);
  36786. };
  36787. /**
  36788. * Invert the geometry to move from a right handed system to a left handed one.
  36789. */
  36790. Geometry.prototype.toLeftHanded = function () {
  36791. // Flip faces
  36792. var tIndices = this.getIndices(false);
  36793. if (tIndices != null && tIndices.length > 0) {
  36794. for (var i = 0; i < tIndices.length; i += 3) {
  36795. var tTemp = tIndices[i + 0];
  36796. tIndices[i + 0] = tIndices[i + 2];
  36797. tIndices[i + 2] = tTemp;
  36798. }
  36799. this.setIndices(tIndices);
  36800. }
  36801. // Negate position.z
  36802. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36803. if (tPositions != null && tPositions.length > 0) {
  36804. for (var i = 0; i < tPositions.length; i += 3) {
  36805. tPositions[i + 2] = -tPositions[i + 2];
  36806. }
  36807. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36808. }
  36809. // Negate normal.z
  36810. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36811. if (tNormals != null && tNormals.length > 0) {
  36812. for (var i = 0; i < tNormals.length; i += 3) {
  36813. tNormals[i + 2] = -tNormals[i + 2];
  36814. }
  36815. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36816. }
  36817. };
  36818. // Cache
  36819. /** @ignore */
  36820. Geometry.prototype._resetPointsArrayCache = function () {
  36821. this._positions = null;
  36822. };
  36823. /** @ignore */
  36824. Geometry.prototype._generatePointsArray = function () {
  36825. if (this._positions)
  36826. return true;
  36827. this._positions = [];
  36828. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36829. if (!data) {
  36830. return false;
  36831. }
  36832. for (var index = 0; index < data.length; index += 3) {
  36833. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  36834. }
  36835. return true;
  36836. };
  36837. /**
  36838. * Gets a value indicating if the geometry is disposed
  36839. * @returns true if the geometry was disposed
  36840. */
  36841. Geometry.prototype.isDisposed = function () {
  36842. return this._isDisposed;
  36843. };
  36844. Geometry.prototype._disposeVertexArrayObjects = function () {
  36845. if (this._vertexArrayObjects) {
  36846. for (var kind in this._vertexArrayObjects) {
  36847. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  36848. }
  36849. this._vertexArrayObjects = {};
  36850. }
  36851. };
  36852. /**
  36853. * Free all associated resources
  36854. */
  36855. Geometry.prototype.dispose = function () {
  36856. var meshes = this._meshes;
  36857. var numOfMeshes = meshes.length;
  36858. var index;
  36859. for (index = 0; index < numOfMeshes; index++) {
  36860. this.releaseForMesh(meshes[index]);
  36861. }
  36862. this._meshes = [];
  36863. this._disposeVertexArrayObjects();
  36864. for (var kind in this._vertexBuffers) {
  36865. this._vertexBuffers[kind].dispose();
  36866. }
  36867. this._vertexBuffers = {};
  36868. this._totalVertices = 0;
  36869. if (this._indexBuffer) {
  36870. this._engine._releaseBuffer(this._indexBuffer);
  36871. }
  36872. this._indexBuffer = null;
  36873. this._indices = [];
  36874. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36875. this.delayLoadingFile = null;
  36876. this._delayLoadingFunction = null;
  36877. this._delayInfo = [];
  36878. this._boundingInfo = null;
  36879. this._scene.removeGeometry(this);
  36880. this._isDisposed = true;
  36881. };
  36882. /**
  36883. * Clone the current geometry into a new geometry
  36884. * @param id defines the unique ID of the new geometry
  36885. * @returns a new geometry object
  36886. */
  36887. Geometry.prototype.copy = function (id) {
  36888. var vertexData = new BABYLON.VertexData();
  36889. vertexData.indices = [];
  36890. var indices = this.getIndices();
  36891. if (indices) {
  36892. for (var index = 0; index < indices.length; index++) {
  36893. vertexData.indices.push(indices[index]);
  36894. }
  36895. }
  36896. var updatable = false;
  36897. var stopChecking = false;
  36898. var kind;
  36899. for (kind in this._vertexBuffers) {
  36900. // using slice() to make a copy of the array and not just reference it
  36901. var data = this.getVerticesData(kind);
  36902. if (data instanceof Float32Array) {
  36903. vertexData.set(new Float32Array(data), kind);
  36904. }
  36905. else {
  36906. vertexData.set(data.slice(0), kind);
  36907. }
  36908. if (!stopChecking) {
  36909. var vb = this.getVertexBuffer(kind);
  36910. if (vb) {
  36911. updatable = vb.isUpdatable();
  36912. stopChecking = !updatable;
  36913. }
  36914. }
  36915. }
  36916. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  36917. geometry.delayLoadState = this.delayLoadState;
  36918. geometry.delayLoadingFile = this.delayLoadingFile;
  36919. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36920. for (kind in this._delayInfo) {
  36921. geometry._delayInfo = geometry._delayInfo || [];
  36922. geometry._delayInfo.push(kind);
  36923. }
  36924. // Bounding info
  36925. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36926. return geometry;
  36927. };
  36928. /**
  36929. * Serialize the current geometry info (and not the vertices data) into a JSON object
  36930. * @return a JSON representation of the current geometry data (without the vertices data)
  36931. */
  36932. Geometry.prototype.serialize = function () {
  36933. var serializationObject = {};
  36934. serializationObject.id = this.id;
  36935. serializationObject.updatable = this._updatable;
  36936. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  36937. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36938. }
  36939. return serializationObject;
  36940. };
  36941. Geometry.prototype.toNumberArray = function (origin) {
  36942. if (Array.isArray(origin)) {
  36943. return origin;
  36944. }
  36945. else {
  36946. return Array.prototype.slice.call(origin);
  36947. }
  36948. };
  36949. /**
  36950. * Serialize all vertices data into a JSON oject
  36951. * @returns a JSON representation of the current geometry data
  36952. */
  36953. Geometry.prototype.serializeVerticeData = function () {
  36954. var serializationObject = this.serialize();
  36955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36956. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  36957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  36958. serializationObject.positions._updatable = true;
  36959. }
  36960. }
  36961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36962. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  36963. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  36964. serializationObject.normals._updatable = true;
  36965. }
  36966. }
  36967. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36968. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  36969. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  36970. serializationObject.tangets._updatable = true;
  36971. }
  36972. }
  36973. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36974. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  36975. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  36976. serializationObject.uvs._updatable = true;
  36977. }
  36978. }
  36979. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36980. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  36981. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  36982. serializationObject.uv2s._updatable = true;
  36983. }
  36984. }
  36985. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36986. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  36987. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  36988. serializationObject.uv3s._updatable = true;
  36989. }
  36990. }
  36991. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36992. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  36993. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  36994. serializationObject.uv4s._updatable = true;
  36995. }
  36996. }
  36997. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36998. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  36999. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  37000. serializationObject.uv5s._updatable = true;
  37001. }
  37002. }
  37003. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37004. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  37005. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  37006. serializationObject.uv6s._updatable = true;
  37007. }
  37008. }
  37009. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37010. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  37011. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  37012. serializationObject.colors._updatable = true;
  37013. }
  37014. }
  37015. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37016. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  37017. serializationObject.matricesIndices._isExpanded = true;
  37018. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37019. serializationObject.matricesIndices._updatable = true;
  37020. }
  37021. }
  37022. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37023. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  37024. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37025. serializationObject.matricesWeights._updatable = true;
  37026. }
  37027. }
  37028. serializationObject.indices = this.toNumberArray(this.getIndices());
  37029. return serializationObject;
  37030. };
  37031. // Statics
  37032. /**
  37033. * Extracts a clone of a mesh geometry
  37034. * @param mesh defines the source mesh
  37035. * @param id defines the unique ID of the new geometry object
  37036. * @returns the new geometry object
  37037. */
  37038. Geometry.ExtractFromMesh = function (mesh, id) {
  37039. var geometry = mesh._geometry;
  37040. if (!geometry) {
  37041. return null;
  37042. }
  37043. return geometry.copy(id);
  37044. };
  37045. /**
  37046. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  37047. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  37048. * Be aware Math.random() could cause collisions, but:
  37049. * "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"
  37050. * @returns a string containing a new GUID
  37051. */
  37052. Geometry.RandomId = function () {
  37053. return BABYLON.Tools.RandomId();
  37054. };
  37055. /** @ignore */
  37056. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  37057. var scene = mesh.getScene();
  37058. // Geometry
  37059. var geometryId = parsedGeometry.geometryId;
  37060. if (geometryId) {
  37061. var geometry = scene.getGeometryByID(geometryId);
  37062. if (geometry) {
  37063. geometry.applyToMesh(mesh);
  37064. }
  37065. }
  37066. else if (parsedGeometry instanceof ArrayBuffer) {
  37067. var binaryInfo = mesh._binaryInfo;
  37068. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  37069. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  37070. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  37071. }
  37072. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  37073. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  37074. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  37075. }
  37076. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  37077. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  37078. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  37079. }
  37080. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  37081. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  37082. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  37083. }
  37084. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  37085. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  37086. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  37087. }
  37088. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  37089. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  37090. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  37091. }
  37092. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  37093. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  37094. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  37095. }
  37096. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  37097. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  37098. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  37099. }
  37100. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  37101. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  37102. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  37103. }
  37104. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  37105. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  37106. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  37107. }
  37108. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  37109. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  37110. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  37111. }
  37112. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  37113. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  37114. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  37115. }
  37116. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  37117. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  37118. mesh.setIndices(indicesData, null);
  37119. }
  37120. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  37121. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  37122. mesh.subMeshes = [];
  37123. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  37124. var materialIndex = subMeshesData[(i * 5) + 0];
  37125. var verticesStart = subMeshesData[(i * 5) + 1];
  37126. var verticesCount = subMeshesData[(i * 5) + 2];
  37127. var indexStart = subMeshesData[(i * 5) + 3];
  37128. var indexCount = subMeshesData[(i * 5) + 4];
  37129. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  37130. }
  37131. }
  37132. }
  37133. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  37134. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  37135. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  37136. if (parsedGeometry.tangents) {
  37137. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  37138. }
  37139. if (parsedGeometry.uvs) {
  37140. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  37141. }
  37142. if (parsedGeometry.uvs2) {
  37143. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  37144. }
  37145. if (parsedGeometry.uvs3) {
  37146. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  37147. }
  37148. if (parsedGeometry.uvs4) {
  37149. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  37150. }
  37151. if (parsedGeometry.uvs5) {
  37152. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  37153. }
  37154. if (parsedGeometry.uvs6) {
  37155. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  37156. }
  37157. if (parsedGeometry.colors) {
  37158. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  37159. }
  37160. if (parsedGeometry.matricesIndices) {
  37161. if (!parsedGeometry.matricesIndices._isExpanded) {
  37162. var floatIndices = [];
  37163. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  37164. var matricesIndex = parsedGeometry.matricesIndices[i];
  37165. floatIndices.push(matricesIndex & 0x000000FF);
  37166. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37167. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37168. floatIndices.push(matricesIndex >> 24);
  37169. }
  37170. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  37171. }
  37172. else {
  37173. delete parsedGeometry.matricesIndices._isExpanded;
  37174. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  37175. }
  37176. }
  37177. if (parsedGeometry.matricesIndicesExtra) {
  37178. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  37179. var floatIndices = [];
  37180. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  37181. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  37182. floatIndices.push(matricesIndex & 0x000000FF);
  37183. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37184. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37185. floatIndices.push(matricesIndex >> 24);
  37186. }
  37187. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  37188. }
  37189. else {
  37190. delete parsedGeometry.matricesIndices._isExpanded;
  37191. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  37192. }
  37193. }
  37194. if (parsedGeometry.matricesWeights) {
  37195. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  37196. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  37197. }
  37198. if (parsedGeometry.matricesWeightsExtra) {
  37199. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  37200. }
  37201. mesh.setIndices(parsedGeometry.indices, null);
  37202. }
  37203. // SubMeshes
  37204. if (parsedGeometry.subMeshes) {
  37205. mesh.subMeshes = [];
  37206. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  37207. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  37208. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  37209. }
  37210. }
  37211. // Flat shading
  37212. if (mesh._shouldGenerateFlatShading) {
  37213. mesh.convertToFlatShadedMesh();
  37214. delete mesh._shouldGenerateFlatShading;
  37215. }
  37216. // Update
  37217. mesh.computeWorldMatrix(true);
  37218. // Octree
  37219. var sceneOctree = scene.selectionOctree;
  37220. if (sceneOctree !== undefined && sceneOctree !== null) {
  37221. sceneOctree.addMesh(mesh);
  37222. }
  37223. };
  37224. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  37225. var epsilon = 1e-3;
  37226. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  37227. return;
  37228. }
  37229. var noInfluenceBoneIndex = 0.0;
  37230. if (parsedGeometry.skeletonId > -1) {
  37231. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  37232. if (!skeleton) {
  37233. return;
  37234. }
  37235. noInfluenceBoneIndex = skeleton.bones.length;
  37236. }
  37237. else {
  37238. return;
  37239. }
  37240. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  37241. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37242. var matricesWeights = parsedGeometry.matricesWeights;
  37243. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  37244. var influencers = parsedGeometry.numBoneInfluencer;
  37245. var size = matricesWeights.length;
  37246. for (var i = 0; i < size; i += 4) {
  37247. var weight = 0.0;
  37248. var firstZeroWeight = -1;
  37249. for (var j = 0; j < 4; j++) {
  37250. var w = matricesWeights[i + j];
  37251. weight += w;
  37252. if (w < epsilon && firstZeroWeight < 0) {
  37253. firstZeroWeight = j;
  37254. }
  37255. }
  37256. if (matricesWeightsExtra) {
  37257. for (var j = 0; j < 4; j++) {
  37258. var w = matricesWeightsExtra[i + j];
  37259. weight += w;
  37260. if (w < epsilon && firstZeroWeight < 0) {
  37261. firstZeroWeight = j + 4;
  37262. }
  37263. }
  37264. }
  37265. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  37266. firstZeroWeight = influencers - 1;
  37267. }
  37268. if (weight > epsilon) {
  37269. var mweight = 1.0 / weight;
  37270. for (var j = 0; j < 4; j++) {
  37271. matricesWeights[i + j] *= mweight;
  37272. }
  37273. if (matricesWeightsExtra) {
  37274. for (var j = 0; j < 4; j++) {
  37275. matricesWeightsExtra[i + j] *= mweight;
  37276. }
  37277. }
  37278. }
  37279. else {
  37280. if (firstZeroWeight >= 4) {
  37281. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  37282. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  37283. }
  37284. else {
  37285. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  37286. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  37287. }
  37288. }
  37289. }
  37290. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  37291. if (parsedGeometry.matricesWeightsExtra) {
  37292. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  37293. }
  37294. };
  37295. /**
  37296. * Create a new geometry from persisted data (Using .babylon file format)
  37297. * @param parsedVertexData defines the persisted data
  37298. * @param scene defines the hosting scene
  37299. * @param rootUrl defines the root url to use to load assets (like delayed data)
  37300. * @returns the new geometry object
  37301. */
  37302. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  37303. if (scene.getGeometryByID(parsedVertexData.id)) {
  37304. return null; // null since geometry could be something else than a box...
  37305. }
  37306. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  37307. if (BABYLON.Tags) {
  37308. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  37309. }
  37310. if (parsedVertexData.delayLoadingFile) {
  37311. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37312. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  37313. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  37314. geometry._delayInfo = [];
  37315. if (parsedVertexData.hasUVs) {
  37316. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  37317. }
  37318. if (parsedVertexData.hasUVs2) {
  37319. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  37320. }
  37321. if (parsedVertexData.hasUVs3) {
  37322. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  37323. }
  37324. if (parsedVertexData.hasUVs4) {
  37325. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  37326. }
  37327. if (parsedVertexData.hasUVs5) {
  37328. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  37329. }
  37330. if (parsedVertexData.hasUVs6) {
  37331. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  37332. }
  37333. if (parsedVertexData.hasColors) {
  37334. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  37335. }
  37336. if (parsedVertexData.hasMatricesIndices) {
  37337. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37338. }
  37339. if (parsedVertexData.hasMatricesWeights) {
  37340. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37341. }
  37342. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  37343. }
  37344. else {
  37345. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  37346. }
  37347. scene.pushGeometry(geometry, true);
  37348. return geometry;
  37349. };
  37350. return Geometry;
  37351. }());
  37352. BABYLON.Geometry = Geometry;
  37353. // Primitives
  37354. /// Abstract class
  37355. /**
  37356. * Abstract class used to provide common services for all typed geometries
  37357. */
  37358. var _PrimitiveGeometry = /** @class */ (function (_super) {
  37359. __extends(_PrimitiveGeometry, _super);
  37360. /**
  37361. * Creates a new typed geometry
  37362. * @param id defines the unique ID of the geometry
  37363. * @param scene defines the hosting scene
  37364. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37365. * @param mesh defines the hosting mesh (can be null)
  37366. */
  37367. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  37368. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  37369. if (mesh === void 0) { mesh = null; }
  37370. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  37371. _this._canBeRegenerated = _canBeRegenerated;
  37372. _this._beingRegenerated = true;
  37373. _this.regenerate();
  37374. _this._beingRegenerated = false;
  37375. return _this;
  37376. }
  37377. /**
  37378. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  37379. * @returns true if the geometry can be regenerated
  37380. */
  37381. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  37382. return this._canBeRegenerated;
  37383. };
  37384. /**
  37385. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  37386. */
  37387. _PrimitiveGeometry.prototype.regenerate = function () {
  37388. if (!this._canBeRegenerated) {
  37389. return;
  37390. }
  37391. this._beingRegenerated = true;
  37392. this.setAllVerticesData(this._regenerateVertexData(), false);
  37393. this._beingRegenerated = false;
  37394. };
  37395. /**
  37396. * Clone the geometry
  37397. * @param id defines the unique ID of the new geometry
  37398. * @returns the new geometry
  37399. */
  37400. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  37401. return _super.prototype.copy.call(this, id);
  37402. };
  37403. // overrides
  37404. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37405. if (!this._beingRegenerated) {
  37406. return;
  37407. }
  37408. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  37409. };
  37410. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  37411. if (!this._beingRegenerated) {
  37412. return;
  37413. }
  37414. _super.prototype.setVerticesData.call(this, kind, data, false);
  37415. };
  37416. // to override
  37417. /** @ignore */
  37418. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  37419. throw new Error("Abstract method");
  37420. };
  37421. _PrimitiveGeometry.prototype.copy = function (id) {
  37422. throw new Error("Must be overriden in sub-classes.");
  37423. };
  37424. _PrimitiveGeometry.prototype.serialize = function () {
  37425. var serializationObject = _super.prototype.serialize.call(this);
  37426. serializationObject.canBeRegenerated = this.canBeRegenerated();
  37427. return serializationObject;
  37428. };
  37429. return _PrimitiveGeometry;
  37430. }(Geometry));
  37431. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  37432. /**
  37433. * Creates a ribbon geometry
  37434. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  37435. */
  37436. var RibbonGeometry = /** @class */ (function (_super) {
  37437. __extends(RibbonGeometry, _super);
  37438. /**
  37439. * Creates a ribbon geometry
  37440. * @param id defines the unique ID of the geometry
  37441. * @param scene defines the hosting scene
  37442. * @param pathArray defines the array of paths to use
  37443. * @param closeArray defines if the last path and the first path must be joined
  37444. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  37445. * @param offset defines the offset between points
  37446. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37447. * @param mesh defines the hosting mesh (can be null)
  37448. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37449. */
  37450. function RibbonGeometry(id, scene,
  37451. /**
  37452. * Defines the array of paths to use
  37453. */
  37454. pathArray,
  37455. /**
  37456. * Defines if the last and first points of each path in your pathArray must be joined
  37457. */
  37458. closeArray,
  37459. /**
  37460. * Defines if the last and first points of each path in your pathArray must be joined
  37461. */
  37462. closePath,
  37463. /**
  37464. * Defines the offset between points
  37465. */
  37466. offset, canBeRegenerated, mesh,
  37467. /**
  37468. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37469. */
  37470. side) {
  37471. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37472. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37473. _this.pathArray = pathArray;
  37474. _this.closeArray = closeArray;
  37475. _this.closePath = closePath;
  37476. _this.offset = offset;
  37477. _this.side = side;
  37478. return _this;
  37479. }
  37480. /** @ignore */
  37481. RibbonGeometry.prototype._regenerateVertexData = function () {
  37482. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  37483. };
  37484. RibbonGeometry.prototype.copy = function (id) {
  37485. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  37486. };
  37487. return RibbonGeometry;
  37488. }(_PrimitiveGeometry));
  37489. BABYLON.RibbonGeometry = RibbonGeometry;
  37490. /**
  37491. * Creates a box geometry
  37492. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  37493. */
  37494. var BoxGeometry = /** @class */ (function (_super) {
  37495. __extends(BoxGeometry, _super);
  37496. /**
  37497. * Creates a box geometry
  37498. * @param id defines the unique ID of the geometry
  37499. * @param scene defines the hosting scene
  37500. * @param size defines the zise of the box (width, height and depth are the same)
  37501. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37502. * @param mesh defines the hosting mesh (can be null)
  37503. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37504. */
  37505. function BoxGeometry(id, scene,
  37506. /**
  37507. * Defines the zise of the box (width, height and depth are the same)
  37508. */
  37509. size, canBeRegenerated, mesh,
  37510. /**
  37511. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37512. */
  37513. side) {
  37514. if (mesh === void 0) { mesh = null; }
  37515. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37516. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37517. _this.size = size;
  37518. _this.side = side;
  37519. return _this;
  37520. }
  37521. BoxGeometry.prototype._regenerateVertexData = function () {
  37522. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  37523. };
  37524. BoxGeometry.prototype.copy = function (id) {
  37525. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  37526. };
  37527. BoxGeometry.prototype.serialize = function () {
  37528. var serializationObject = _super.prototype.serialize.call(this);
  37529. serializationObject.size = this.size;
  37530. return serializationObject;
  37531. };
  37532. BoxGeometry.Parse = function (parsedBox, scene) {
  37533. if (scene.getGeometryByID(parsedBox.id)) {
  37534. return null; // null since geometry could be something else than a box...
  37535. }
  37536. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  37537. if (BABYLON.Tags) {
  37538. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  37539. }
  37540. scene.pushGeometry(box, true);
  37541. return box;
  37542. };
  37543. return BoxGeometry;
  37544. }(_PrimitiveGeometry));
  37545. BABYLON.BoxGeometry = BoxGeometry;
  37546. /**
  37547. * Creates a sphere geometry
  37548. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  37549. */
  37550. var SphereGeometry = /** @class */ (function (_super) {
  37551. __extends(SphereGeometry, _super);
  37552. /**
  37553. * Create a new sphere geometry
  37554. * @param id defines the unique ID of the geometry
  37555. * @param scene defines the hosting scene
  37556. * @param segments defines the number of segments to use to create the sphere
  37557. * @param diameter defines the diameter of the sphere
  37558. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37559. * @param mesh defines the hosting mesh (can be null)
  37560. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37561. */
  37562. function SphereGeometry(id, scene,
  37563. /**
  37564. * Defines the number of segments to use to create the sphere
  37565. */
  37566. segments,
  37567. /**
  37568. * Defines the diameter of the sphere
  37569. */
  37570. diameter, canBeRegenerated, mesh,
  37571. /**
  37572. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37573. */
  37574. side) {
  37575. if (mesh === void 0) { mesh = null; }
  37576. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37577. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37578. _this.segments = segments;
  37579. _this.diameter = diameter;
  37580. _this.side = side;
  37581. return _this;
  37582. }
  37583. SphereGeometry.prototype._regenerateVertexData = function () {
  37584. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  37585. };
  37586. SphereGeometry.prototype.copy = function (id) {
  37587. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  37588. };
  37589. SphereGeometry.prototype.serialize = function () {
  37590. var serializationObject = _super.prototype.serialize.call(this);
  37591. serializationObject.segments = this.segments;
  37592. serializationObject.diameter = this.diameter;
  37593. return serializationObject;
  37594. };
  37595. SphereGeometry.Parse = function (parsedSphere, scene) {
  37596. if (scene.getGeometryByID(parsedSphere.id)) {
  37597. return null; // null since geometry could be something else than a sphere...
  37598. }
  37599. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37600. if (BABYLON.Tags) {
  37601. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37602. }
  37603. scene.pushGeometry(sphere, true);
  37604. return sphere;
  37605. };
  37606. return SphereGeometry;
  37607. }(_PrimitiveGeometry));
  37608. BABYLON.SphereGeometry = SphereGeometry;
  37609. /**
  37610. * Creates a disc geometry
  37611. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  37612. */
  37613. var DiscGeometry = /** @class */ (function (_super) {
  37614. __extends(DiscGeometry, _super);
  37615. /**
  37616. * Creates a new disc geometry
  37617. * @param id defines the unique ID of the geometry
  37618. * @param scene defines the hosting scene
  37619. * @param radius defines the radius of the disc
  37620. * @param tessellation defines the tesselation factor to apply to the disc
  37621. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37622. * @param mesh defines the hosting mesh (can be null)
  37623. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37624. */
  37625. function DiscGeometry(id, scene,
  37626. /**
  37627. * Defines the radius of the disc
  37628. */
  37629. radius,
  37630. /**
  37631. * Defines the tesselation factor to apply to the disc
  37632. */
  37633. tessellation, canBeRegenerated, mesh,
  37634. /**
  37635. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37636. */
  37637. side) {
  37638. if (mesh === void 0) { mesh = null; }
  37639. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37640. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37641. _this.radius = radius;
  37642. _this.tessellation = tessellation;
  37643. _this.side = side;
  37644. return _this;
  37645. }
  37646. DiscGeometry.prototype._regenerateVertexData = function () {
  37647. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37648. };
  37649. DiscGeometry.prototype.copy = function (id) {
  37650. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37651. };
  37652. return DiscGeometry;
  37653. }(_PrimitiveGeometry));
  37654. BABYLON.DiscGeometry = DiscGeometry;
  37655. /**
  37656. * Creates a new cylinder geometry
  37657. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  37658. */
  37659. var CylinderGeometry = /** @class */ (function (_super) {
  37660. __extends(CylinderGeometry, _super);
  37661. /**
  37662. * Creates a new cylinder geometry
  37663. * @param id defines the unique ID of the geometry
  37664. * @param scene defines the hosting scene
  37665. * @param height defines the height of the cylinder
  37666. * @param diameterTop defines the diameter of the cylinder's top cap
  37667. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  37668. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  37669. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  37670. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37671. * @param mesh defines the hosting mesh (can be null)
  37672. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37673. */
  37674. function CylinderGeometry(id, scene,
  37675. /**
  37676. * Defines the height of the cylinder
  37677. */
  37678. height,
  37679. /**
  37680. * Defines the diameter of the cylinder's top cap
  37681. */
  37682. diameterTop,
  37683. /**
  37684. * Defines the diameter of the cylinder's bottom cap
  37685. */
  37686. diameterBottom,
  37687. /**
  37688. * Defines the tessellation factor to apply to the cylinder
  37689. */
  37690. tessellation,
  37691. /**
  37692. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  37693. */
  37694. subdivisions, canBeRegenerated, mesh,
  37695. /**
  37696. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37697. */
  37698. side) {
  37699. if (subdivisions === void 0) { subdivisions = 1; }
  37700. if (mesh === void 0) { mesh = null; }
  37701. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37702. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37703. _this.height = height;
  37704. _this.diameterTop = diameterTop;
  37705. _this.diameterBottom = diameterBottom;
  37706. _this.tessellation = tessellation;
  37707. _this.subdivisions = subdivisions;
  37708. _this.side = side;
  37709. return _this;
  37710. }
  37711. CylinderGeometry.prototype._regenerateVertexData = function () {
  37712. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37713. };
  37714. CylinderGeometry.prototype.copy = function (id) {
  37715. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37716. };
  37717. CylinderGeometry.prototype.serialize = function () {
  37718. var serializationObject = _super.prototype.serialize.call(this);
  37719. serializationObject.height = this.height;
  37720. serializationObject.diameterTop = this.diameterTop;
  37721. serializationObject.diameterBottom = this.diameterBottom;
  37722. serializationObject.tessellation = this.tessellation;
  37723. return serializationObject;
  37724. };
  37725. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  37726. if (scene.getGeometryByID(parsedCylinder.id)) {
  37727. return null; // null since geometry could be something else than a cylinder...
  37728. }
  37729. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37730. if (BABYLON.Tags) {
  37731. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37732. }
  37733. scene.pushGeometry(cylinder, true);
  37734. return cylinder;
  37735. };
  37736. return CylinderGeometry;
  37737. }(_PrimitiveGeometry));
  37738. BABYLON.CylinderGeometry = CylinderGeometry;
  37739. /**
  37740. * Creates a new torus geometry
  37741. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  37742. */
  37743. var TorusGeometry = /** @class */ (function (_super) {
  37744. __extends(TorusGeometry, _super);
  37745. /**
  37746. * Creates a new torus geometry
  37747. * @param id defines the unique ID of the geometry
  37748. * @param scene defines the hosting scene
  37749. * @param diameter defines the diameter of the torus
  37750. * @param thickness defines the thickness of the torus (ie. internal diameter)
  37751. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  37752. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37753. * @param mesh defines the hosting mesh (can be null)
  37754. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37755. */
  37756. function TorusGeometry(id, scene,
  37757. /**
  37758. * Defines the diameter of the torus
  37759. */
  37760. diameter,
  37761. /**
  37762. * Defines the thickness of the torus (ie. internal diameter)
  37763. */
  37764. thickness,
  37765. /**
  37766. * Defines the tesselation factor to apply to the torus
  37767. */
  37768. tessellation, canBeRegenerated, mesh,
  37769. /**
  37770. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37771. */
  37772. side) {
  37773. if (mesh === void 0) { mesh = null; }
  37774. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37775. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37776. _this.diameter = diameter;
  37777. _this.thickness = thickness;
  37778. _this.tessellation = tessellation;
  37779. _this.side = side;
  37780. return _this;
  37781. }
  37782. TorusGeometry.prototype._regenerateVertexData = function () {
  37783. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37784. };
  37785. TorusGeometry.prototype.copy = function (id) {
  37786. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37787. };
  37788. TorusGeometry.prototype.serialize = function () {
  37789. var serializationObject = _super.prototype.serialize.call(this);
  37790. serializationObject.diameter = this.diameter;
  37791. serializationObject.thickness = this.thickness;
  37792. serializationObject.tessellation = this.tessellation;
  37793. return serializationObject;
  37794. };
  37795. TorusGeometry.Parse = function (parsedTorus, scene) {
  37796. if (scene.getGeometryByID(parsedTorus.id)) {
  37797. return null; // null since geometry could be something else than a torus...
  37798. }
  37799. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37800. if (BABYLON.Tags) {
  37801. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37802. }
  37803. scene.pushGeometry(torus, true);
  37804. return torus;
  37805. };
  37806. return TorusGeometry;
  37807. }(_PrimitiveGeometry));
  37808. BABYLON.TorusGeometry = TorusGeometry;
  37809. /**
  37810. * Creates a new ground geometry
  37811. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  37812. */
  37813. var GroundGeometry = /** @class */ (function (_super) {
  37814. __extends(GroundGeometry, _super);
  37815. /**
  37816. * Creates a new ground geometry
  37817. * @param id defines the unique ID of the geometry
  37818. * @param scene defines the hosting scene
  37819. * @param width defines the width of the ground
  37820. * @param height defines the height of the ground
  37821. * @param subdivisions defines the subdivisions to apply to the ground
  37822. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37823. * @param mesh defines the hosting mesh (can be null)
  37824. */
  37825. function GroundGeometry(id, scene,
  37826. /**
  37827. * Defines the width of the ground
  37828. */
  37829. width,
  37830. /**
  37831. * Defines the height of the ground
  37832. */
  37833. height,
  37834. /**
  37835. * Defines the subdivisions to apply to the ground
  37836. */
  37837. subdivisions, canBeRegenerated, mesh) {
  37838. if (mesh === void 0) { mesh = null; }
  37839. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37840. _this.width = width;
  37841. _this.height = height;
  37842. _this.subdivisions = subdivisions;
  37843. return _this;
  37844. }
  37845. GroundGeometry.prototype._regenerateVertexData = function () {
  37846. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37847. };
  37848. GroundGeometry.prototype.copy = function (id) {
  37849. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37850. };
  37851. GroundGeometry.prototype.serialize = function () {
  37852. var serializationObject = _super.prototype.serialize.call(this);
  37853. serializationObject.width = this.width;
  37854. serializationObject.height = this.height;
  37855. serializationObject.subdivisions = this.subdivisions;
  37856. return serializationObject;
  37857. };
  37858. GroundGeometry.Parse = function (parsedGround, scene) {
  37859. if (scene.getGeometryByID(parsedGround.id)) {
  37860. return null; // null since geometry could be something else than a ground...
  37861. }
  37862. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37863. if (BABYLON.Tags) {
  37864. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37865. }
  37866. scene.pushGeometry(ground, true);
  37867. return ground;
  37868. };
  37869. return GroundGeometry;
  37870. }(_PrimitiveGeometry));
  37871. BABYLON.GroundGeometry = GroundGeometry;
  37872. /**
  37873. * Creates a tiled ground geometry
  37874. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  37875. */
  37876. var TiledGroundGeometry = /** @class */ (function (_super) {
  37877. __extends(TiledGroundGeometry, _super);
  37878. /**
  37879. * Creates a tiled ground geometry
  37880. * @param id defines the unique ID of the geometry
  37881. * @param scene defines the hosting scene
  37882. * @param xmin defines the minimum value on X axis
  37883. * @param zmin defines the minimum value on Z axis
  37884. * @param xmax defines the maximum value on X axis
  37885. * @param zmax defines the maximum value on Z axis
  37886. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  37887. * @param precision defines the precision to use when computing the tiles
  37888. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37889. * @param mesh defines the hosting mesh (can be null)
  37890. */
  37891. function TiledGroundGeometry(id, scene,
  37892. /**
  37893. * Defines the minimum value on X axis
  37894. */
  37895. xmin,
  37896. /**
  37897. * Defines the minimum value on Z axis
  37898. */
  37899. zmin,
  37900. /**
  37901. * Defines the maximum value on X axis
  37902. */
  37903. xmax,
  37904. /**
  37905. * Defines the maximum value on Z axis
  37906. */
  37907. zmax,
  37908. /**
  37909. * Defines the subdivisions to apply to the ground
  37910. */
  37911. subdivisions,
  37912. /**
  37913. * Defines the precision to use when computing the tiles
  37914. */
  37915. precision, canBeRegenerated, mesh) {
  37916. if (mesh === void 0) { mesh = null; }
  37917. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37918. _this.xmin = xmin;
  37919. _this.zmin = zmin;
  37920. _this.xmax = xmax;
  37921. _this.zmax = zmax;
  37922. _this.subdivisions = subdivisions;
  37923. _this.precision = precision;
  37924. return _this;
  37925. }
  37926. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  37927. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37928. };
  37929. TiledGroundGeometry.prototype.copy = function (id) {
  37930. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37931. };
  37932. return TiledGroundGeometry;
  37933. }(_PrimitiveGeometry));
  37934. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  37935. /**
  37936. * Creates a plane geometry
  37937. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  37938. */
  37939. var PlaneGeometry = /** @class */ (function (_super) {
  37940. __extends(PlaneGeometry, _super);
  37941. /**
  37942. * Creates a plane geometry
  37943. * @param id defines the unique ID of the geometry
  37944. * @param scene defines the hosting scene
  37945. * @param size defines the size of the plane (width === height)
  37946. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37947. * @param mesh defines the hosting mesh (can be null)
  37948. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37949. */
  37950. function PlaneGeometry(id, scene,
  37951. /**
  37952. * Defines the size of the plane (width === height)
  37953. */
  37954. size, canBeRegenerated, mesh,
  37955. /**
  37956. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37957. */
  37958. side) {
  37959. if (mesh === void 0) { mesh = null; }
  37960. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37961. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37962. _this.size = size;
  37963. _this.side = side;
  37964. return _this;
  37965. }
  37966. PlaneGeometry.prototype._regenerateVertexData = function () {
  37967. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37968. };
  37969. PlaneGeometry.prototype.copy = function (id) {
  37970. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37971. };
  37972. PlaneGeometry.prototype.serialize = function () {
  37973. var serializationObject = _super.prototype.serialize.call(this);
  37974. serializationObject.size = this.size;
  37975. return serializationObject;
  37976. };
  37977. PlaneGeometry.Parse = function (parsedPlane, scene) {
  37978. if (scene.getGeometryByID(parsedPlane.id)) {
  37979. return null; // null since geometry could be something else than a ground...
  37980. }
  37981. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37982. if (BABYLON.Tags) {
  37983. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37984. }
  37985. scene.pushGeometry(plane, true);
  37986. return plane;
  37987. };
  37988. return PlaneGeometry;
  37989. }(_PrimitiveGeometry));
  37990. BABYLON.PlaneGeometry = PlaneGeometry;
  37991. /**
  37992. * Creates a torus knot geometry
  37993. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  37994. */
  37995. var TorusKnotGeometry = /** @class */ (function (_super) {
  37996. __extends(TorusKnotGeometry, _super);
  37997. /**
  37998. * Creates a torus knot geometry
  37999. * @param id defines the unique ID of the geometry
  38000. * @param scene defines the hosting scene
  38001. * @param radius defines the radius of the torus knot
  38002. * @param tube defines the thickness of the torus knot tube
  38003. * @param radialSegments defines the number of radial segments
  38004. * @param tubularSegments defines the number of tubular segments
  38005. * @param p defines the first number of windings
  38006. * @param q defines the second number of windings
  38007. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38008. * @param mesh defines the hosting mesh (can be null)
  38009. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38010. */
  38011. function TorusKnotGeometry(id, scene,
  38012. /**
  38013. * Defines the radius of the torus knot
  38014. */
  38015. radius,
  38016. /**
  38017. * Defines the thickness of the torus knot tube
  38018. */
  38019. tube,
  38020. /**
  38021. * Defines the number of radial segments
  38022. */
  38023. radialSegments,
  38024. /**
  38025. * Defines the number of tubular segments
  38026. */
  38027. tubularSegments,
  38028. /**
  38029. * Defines the first number of windings
  38030. */
  38031. p,
  38032. /**
  38033. * Defines the second number of windings
  38034. */
  38035. q, canBeRegenerated, mesh,
  38036. /**
  38037. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38038. */
  38039. side) {
  38040. if (mesh === void 0) { mesh = null; }
  38041. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38042. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38043. _this.radius = radius;
  38044. _this.tube = tube;
  38045. _this.radialSegments = radialSegments;
  38046. _this.tubularSegments = tubularSegments;
  38047. _this.p = p;
  38048. _this.q = q;
  38049. _this.side = side;
  38050. return _this;
  38051. }
  38052. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  38053. 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 });
  38054. };
  38055. TorusKnotGeometry.prototype.copy = function (id) {
  38056. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  38057. };
  38058. TorusKnotGeometry.prototype.serialize = function () {
  38059. var serializationObject = _super.prototype.serialize.call(this);
  38060. serializationObject.radius = this.radius;
  38061. serializationObject.tube = this.tube;
  38062. serializationObject.radialSegments = this.radialSegments;
  38063. serializationObject.tubularSegments = this.tubularSegments;
  38064. serializationObject.p = this.p;
  38065. serializationObject.q = this.q;
  38066. return serializationObject;
  38067. };
  38068. ;
  38069. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  38070. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  38071. return null; // null since geometry could be something else than a ground...
  38072. }
  38073. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  38074. if (BABYLON.Tags) {
  38075. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  38076. }
  38077. scene.pushGeometry(torusKnot, true);
  38078. return torusKnot;
  38079. };
  38080. return TorusKnotGeometry;
  38081. }(_PrimitiveGeometry));
  38082. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  38083. //}
  38084. })(BABYLON || (BABYLON = {}));
  38085. //# sourceMappingURL=babylon.geometry.js.map
  38086. "use strict";
  38087. var BABYLON;
  38088. (function (BABYLON) {
  38089. /**
  38090. * PostProcessManager is used to manage one or more post processes or post process pipelines
  38091. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  38092. */
  38093. var PostProcessManager = /** @class */ (function () {
  38094. /**
  38095. * Creates a new instance PostProcess
  38096. * @param scene The scene that the post process is associated with.
  38097. */
  38098. function PostProcessManager(scene) {
  38099. this._vertexBuffers = {};
  38100. this._scene = scene;
  38101. }
  38102. PostProcessManager.prototype._prepareBuffers = function () {
  38103. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  38104. return;
  38105. }
  38106. // VBO
  38107. var vertices = [];
  38108. vertices.push(1, 1);
  38109. vertices.push(-1, 1);
  38110. vertices.push(-1, -1);
  38111. vertices.push(1, -1);
  38112. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38113. this._buildIndexBuffer();
  38114. };
  38115. PostProcessManager.prototype._buildIndexBuffer = function () {
  38116. // Indices
  38117. var indices = [];
  38118. indices.push(0);
  38119. indices.push(1);
  38120. indices.push(2);
  38121. indices.push(0);
  38122. indices.push(2);
  38123. indices.push(3);
  38124. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  38125. };
  38126. /**
  38127. * Rebuilds the vertex buffers of the manager.
  38128. */
  38129. PostProcessManager.prototype._rebuild = function () {
  38130. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38131. if (!vb) {
  38132. return;
  38133. }
  38134. vb._rebuild();
  38135. this._buildIndexBuffer();
  38136. };
  38137. // Methods
  38138. /**
  38139. * Prepares a frame to be run through a post process.
  38140. * @param sourceTexture The input texture to the post procesess. (default: null)
  38141. * @param postProcesses An array of post processes to be run. (default: null)
  38142. * @returns True if the post processes were able to be run.
  38143. */
  38144. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  38145. if (sourceTexture === void 0) { sourceTexture = null; }
  38146. if (postProcesses === void 0) { postProcesses = null; }
  38147. var camera = this._scene.activeCamera;
  38148. if (!camera) {
  38149. return false;
  38150. }
  38151. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  38152. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  38153. return false;
  38154. }
  38155. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  38156. return true;
  38157. };
  38158. /**
  38159. * Manually render a set of post processes to a texture.
  38160. * @param postProcesses An array of post processes to be run.
  38161. * @param targetTexture The target texture to render to.
  38162. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  38163. */
  38164. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  38165. if (targetTexture === void 0) { targetTexture = null; }
  38166. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  38167. var engine = this._scene.getEngine();
  38168. for (var index = 0; index < postProcesses.length; index++) {
  38169. if (index < postProcesses.length - 1) {
  38170. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  38171. }
  38172. else {
  38173. if (targetTexture) {
  38174. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  38175. }
  38176. else {
  38177. engine.restoreDefaultFramebuffer();
  38178. }
  38179. }
  38180. var pp = postProcesses[index];
  38181. var effect = pp.apply();
  38182. if (effect) {
  38183. pp.onBeforeRenderObservable.notifyObservers(effect);
  38184. // VBOs
  38185. this._prepareBuffers();
  38186. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38187. // Draw order
  38188. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  38189. pp.onAfterRenderObservable.notifyObservers(effect);
  38190. }
  38191. }
  38192. // Restore depth buffer
  38193. engine.setDepthBuffer(true);
  38194. engine.setDepthWrite(true);
  38195. };
  38196. /**
  38197. * Finalize the result of the output of the postprocesses.
  38198. * @param doNotPresent If true the result will not be displayed to the screen.
  38199. * @param targetTexture The target texture to render to.
  38200. * @param faceIndex The index of the face to bind the target texture to.
  38201. * @param postProcesses The array of post processes to render.
  38202. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  38203. */
  38204. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  38205. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  38206. var camera = this._scene.activeCamera;
  38207. if (!camera) {
  38208. return;
  38209. }
  38210. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  38211. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  38212. return;
  38213. }
  38214. var engine = this._scene.getEngine();
  38215. for (var index = 0, len = postProcesses.length; index < len; index++) {
  38216. var pp = postProcesses[index];
  38217. if (index < len - 1) {
  38218. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  38219. }
  38220. else {
  38221. if (targetTexture) {
  38222. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  38223. }
  38224. else {
  38225. engine.restoreDefaultFramebuffer();
  38226. }
  38227. }
  38228. if (doNotPresent) {
  38229. break;
  38230. }
  38231. var effect = pp.apply();
  38232. if (effect) {
  38233. pp.onBeforeRenderObservable.notifyObservers(effect);
  38234. // VBOs
  38235. this._prepareBuffers();
  38236. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38237. // Draw order
  38238. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  38239. pp.onAfterRenderObservable.notifyObservers(effect);
  38240. }
  38241. }
  38242. // Restore states
  38243. engine.setDepthBuffer(true);
  38244. engine.setDepthWrite(true);
  38245. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38246. };
  38247. /**
  38248. * Disposes of the post process manager.
  38249. */
  38250. PostProcessManager.prototype.dispose = function () {
  38251. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38252. if (buffer) {
  38253. buffer.dispose();
  38254. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38255. }
  38256. if (this._indexBuffer) {
  38257. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38258. this._indexBuffer = null;
  38259. }
  38260. };
  38261. return PostProcessManager;
  38262. }());
  38263. BABYLON.PostProcessManager = PostProcessManager;
  38264. })(BABYLON || (BABYLON = {}));
  38265. //# sourceMappingURL=babylon.postProcessManager.js.map
  38266. "use strict";
  38267. var BABYLON;
  38268. (function (BABYLON) {
  38269. /**
  38270. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  38271. */
  38272. var PerformanceMonitor = /** @class */ (function () {
  38273. /**
  38274. * constructor
  38275. * @param frameSampleSize The number of samples required to saturate the sliding window
  38276. */
  38277. function PerformanceMonitor(frameSampleSize) {
  38278. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  38279. this._enabled = true;
  38280. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  38281. }
  38282. /**
  38283. * Samples current frame
  38284. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  38285. */
  38286. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  38287. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  38288. if (!this._enabled)
  38289. return;
  38290. if (this._lastFrameTimeMs != null) {
  38291. var dt = timeMs - this._lastFrameTimeMs;
  38292. this._rollingFrameTime.add(dt);
  38293. }
  38294. this._lastFrameTimeMs = timeMs;
  38295. };
  38296. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  38297. /**
  38298. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  38299. * @return Average frame time in milliseconds
  38300. */
  38301. get: function () {
  38302. return this._rollingFrameTime.average;
  38303. },
  38304. enumerable: true,
  38305. configurable: true
  38306. });
  38307. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  38308. /**
  38309. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  38310. * @return Frame time variance in milliseconds squared
  38311. */
  38312. get: function () {
  38313. return this._rollingFrameTime.variance;
  38314. },
  38315. enumerable: true,
  38316. configurable: true
  38317. });
  38318. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  38319. /**
  38320. * Returns the frame time of the most recent frame
  38321. * @return Frame time in milliseconds
  38322. */
  38323. get: function () {
  38324. return this._rollingFrameTime.history(0);
  38325. },
  38326. enumerable: true,
  38327. configurable: true
  38328. });
  38329. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  38330. /**
  38331. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  38332. * @return Framerate in frames per second
  38333. */
  38334. get: function () {
  38335. return 1000.0 / this._rollingFrameTime.average;
  38336. },
  38337. enumerable: true,
  38338. configurable: true
  38339. });
  38340. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  38341. /**
  38342. * Returns the average framerate in frames per second using the most recent frame time
  38343. * @return Framerate in frames per second
  38344. */
  38345. get: function () {
  38346. var history = this._rollingFrameTime.history(0);
  38347. if (history === 0) {
  38348. return 0;
  38349. }
  38350. return 1000.0 / history;
  38351. },
  38352. enumerable: true,
  38353. configurable: true
  38354. });
  38355. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  38356. /**
  38357. * Returns true if enough samples have been taken to completely fill the sliding window
  38358. * @return true if saturated
  38359. */
  38360. get: function () {
  38361. return this._rollingFrameTime.isSaturated();
  38362. },
  38363. enumerable: true,
  38364. configurable: true
  38365. });
  38366. /**
  38367. * Enables contributions to the sliding window sample set
  38368. */
  38369. PerformanceMonitor.prototype.enable = function () {
  38370. this._enabled = true;
  38371. };
  38372. /**
  38373. * Disables contributions to the sliding window sample set
  38374. * Samples will not be interpolated over the disabled period
  38375. */
  38376. PerformanceMonitor.prototype.disable = function () {
  38377. this._enabled = false;
  38378. //clear last sample to avoid interpolating over the disabled period when next enabled
  38379. this._lastFrameTimeMs = null;
  38380. };
  38381. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  38382. /**
  38383. * Returns true if sampling is enabled
  38384. * @return true if enabled
  38385. */
  38386. get: function () {
  38387. return this._enabled;
  38388. },
  38389. enumerable: true,
  38390. configurable: true
  38391. });
  38392. /**
  38393. * Resets performance monitor
  38394. */
  38395. PerformanceMonitor.prototype.reset = function () {
  38396. //clear last sample to avoid interpolating over the disabled period when next enabled
  38397. this._lastFrameTimeMs = null;
  38398. //wipe record
  38399. this._rollingFrameTime.reset();
  38400. };
  38401. return PerformanceMonitor;
  38402. }());
  38403. BABYLON.PerformanceMonitor = PerformanceMonitor;
  38404. /**
  38405. * RollingAverage
  38406. *
  38407. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  38408. */
  38409. var RollingAverage = /** @class */ (function () {
  38410. /**
  38411. * constructor
  38412. * @param length The number of samples required to saturate the sliding window
  38413. */
  38414. function RollingAverage(length) {
  38415. this._samples = new Array(length);
  38416. this.reset();
  38417. }
  38418. /**
  38419. * Adds a sample to the sample set
  38420. * @param v The sample value
  38421. */
  38422. RollingAverage.prototype.add = function (v) {
  38423. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  38424. var delta;
  38425. //we need to check if we've already wrapped round
  38426. if (this.isSaturated()) {
  38427. //remove bottom of stack from mean
  38428. var bottomValue = this._samples[this._pos];
  38429. delta = bottomValue - this.average;
  38430. this.average -= delta / (this._sampleCount - 1);
  38431. this._m2 -= delta * (bottomValue - this.average);
  38432. }
  38433. else {
  38434. this._sampleCount++;
  38435. }
  38436. //add new value to mean
  38437. delta = v - this.average;
  38438. this.average += delta / (this._sampleCount);
  38439. this._m2 += delta * (v - this.average);
  38440. //set the new variance
  38441. this.variance = this._m2 / (this._sampleCount - 1);
  38442. this._samples[this._pos] = v;
  38443. this._pos++;
  38444. this._pos %= this._samples.length; //positive wrap around
  38445. };
  38446. /**
  38447. * Returns previously added values or null if outside of history or outside the sliding window domain
  38448. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  38449. * @return Value previously recorded with add() or null if outside of range
  38450. */
  38451. RollingAverage.prototype.history = function (i) {
  38452. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  38453. return 0;
  38454. }
  38455. var i0 = this._wrapPosition(this._pos - 1.0);
  38456. return this._samples[this._wrapPosition(i0 - i)];
  38457. };
  38458. /**
  38459. * Returns true if enough samples have been taken to completely fill the sliding window
  38460. * @return true if sample-set saturated
  38461. */
  38462. RollingAverage.prototype.isSaturated = function () {
  38463. return this._sampleCount >= this._samples.length;
  38464. };
  38465. /**
  38466. * Resets the rolling average (equivalent to 0 samples taken so far)
  38467. */
  38468. RollingAverage.prototype.reset = function () {
  38469. this.average = 0;
  38470. this.variance = 0;
  38471. this._sampleCount = 0;
  38472. this._pos = 0;
  38473. this._m2 = 0;
  38474. };
  38475. /**
  38476. * Wraps a value around the sample range boundaries
  38477. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  38478. * @return Wrapped position in sample range
  38479. */
  38480. RollingAverage.prototype._wrapPosition = function (i) {
  38481. var max = this._samples.length;
  38482. return ((i % max) + max) % max;
  38483. };
  38484. return RollingAverage;
  38485. }());
  38486. BABYLON.RollingAverage = RollingAverage;
  38487. })(BABYLON || (BABYLON = {}));
  38488. //# sourceMappingURL=babylon.performanceMonitor.js.map
  38489. "use strict";
  38490. var BABYLON;
  38491. (function (BABYLON) {
  38492. /**
  38493. * This groups together the common properties used for image processing either in direct forward pass
  38494. * or through post processing effect depending on the use of the image processing pipeline in your scene
  38495. * or not.
  38496. */
  38497. var ImageProcessingConfiguration = /** @class */ (function () {
  38498. function ImageProcessingConfiguration() {
  38499. /**
  38500. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  38501. */
  38502. this.colorCurves = new BABYLON.ColorCurves();
  38503. this._colorCurvesEnabled = false;
  38504. this._colorGradingEnabled = false;
  38505. this._colorGradingWithGreenDepth = true;
  38506. this._colorGradingBGR = true;
  38507. this._exposure = 1.0;
  38508. this._toneMappingEnabled = false;
  38509. this._contrast = 1.0;
  38510. /**
  38511. * Vignette stretch size.
  38512. */
  38513. this.vignetteStretch = 0;
  38514. /**
  38515. * Vignette centre X Offset.
  38516. */
  38517. this.vignetteCentreX = 0;
  38518. /**
  38519. * Vignette centre Y Offset.
  38520. */
  38521. this.vignetteCentreY = 0;
  38522. /**
  38523. * Vignette weight or intensity of the vignette effect.
  38524. */
  38525. this.vignetteWeight = 1.5;
  38526. /**
  38527. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  38528. * if vignetteEnabled is set to true.
  38529. */
  38530. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  38531. /**
  38532. * Camera field of view used by the Vignette effect.
  38533. */
  38534. this.vignetteCameraFov = 0.5;
  38535. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  38536. this._vignetteEnabled = false;
  38537. this._applyByPostProcess = false;
  38538. this._isEnabled = true;
  38539. /**
  38540. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  38541. */
  38542. this.onUpdateParameters = new BABYLON.Observable();
  38543. }
  38544. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  38545. /**
  38546. * Gets wether the color curves effect is enabled.
  38547. */
  38548. get: function () {
  38549. return this._colorCurvesEnabled;
  38550. },
  38551. /**
  38552. * Sets wether the color curves effect is enabled.
  38553. */
  38554. set: function (value) {
  38555. if (this._colorCurvesEnabled === value) {
  38556. return;
  38557. }
  38558. this._colorCurvesEnabled = value;
  38559. this._updateParameters();
  38560. },
  38561. enumerable: true,
  38562. configurable: true
  38563. });
  38564. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  38565. /**
  38566. * Gets wether the color grading effect is enabled.
  38567. */
  38568. get: function () {
  38569. return this._colorGradingEnabled;
  38570. },
  38571. /**
  38572. * Sets wether the color grading effect is enabled.
  38573. */
  38574. set: function (value) {
  38575. if (this._colorGradingEnabled === value) {
  38576. return;
  38577. }
  38578. this._colorGradingEnabled = value;
  38579. this._updateParameters();
  38580. },
  38581. enumerable: true,
  38582. configurable: true
  38583. });
  38584. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  38585. /**
  38586. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  38587. */
  38588. get: function () {
  38589. return this._colorGradingWithGreenDepth;
  38590. },
  38591. /**
  38592. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  38593. */
  38594. set: function (value) {
  38595. if (this._colorGradingWithGreenDepth === value) {
  38596. return;
  38597. }
  38598. this._colorGradingWithGreenDepth = value;
  38599. this._updateParameters();
  38600. },
  38601. enumerable: true,
  38602. configurable: true
  38603. });
  38604. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  38605. /**
  38606. * Gets wether the color grading texture contains BGR values.
  38607. */
  38608. get: function () {
  38609. return this._colorGradingBGR;
  38610. },
  38611. /**
  38612. * Sets wether the color grading texture contains BGR values.
  38613. */
  38614. set: function (value) {
  38615. if (this._colorGradingBGR === value) {
  38616. return;
  38617. }
  38618. this._colorGradingBGR = value;
  38619. this._updateParameters();
  38620. },
  38621. enumerable: true,
  38622. configurable: true
  38623. });
  38624. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  38625. /**
  38626. * Gets the Exposure used in the effect.
  38627. */
  38628. get: function () {
  38629. return this._exposure;
  38630. },
  38631. /**
  38632. * Sets the Exposure used in the effect.
  38633. */
  38634. set: function (value) {
  38635. if (this._exposure === value) {
  38636. return;
  38637. }
  38638. this._exposure = value;
  38639. this._updateParameters();
  38640. },
  38641. enumerable: true,
  38642. configurable: true
  38643. });
  38644. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  38645. /**
  38646. * Gets wether the tone mapping effect is enabled.
  38647. */
  38648. get: function () {
  38649. return this._toneMappingEnabled;
  38650. },
  38651. /**
  38652. * Sets wether the tone mapping effect is enabled.
  38653. */
  38654. set: function (value) {
  38655. if (this._toneMappingEnabled === value) {
  38656. return;
  38657. }
  38658. this._toneMappingEnabled = value;
  38659. this._updateParameters();
  38660. },
  38661. enumerable: true,
  38662. configurable: true
  38663. });
  38664. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  38665. /**
  38666. * Gets the contrast used in the effect.
  38667. */
  38668. get: function () {
  38669. return this._contrast;
  38670. },
  38671. /**
  38672. * Sets the contrast used in the effect.
  38673. */
  38674. set: function (value) {
  38675. if (this._contrast === value) {
  38676. return;
  38677. }
  38678. this._contrast = value;
  38679. this._updateParameters();
  38680. },
  38681. enumerable: true,
  38682. configurable: true
  38683. });
  38684. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  38685. /**
  38686. * Gets the vignette blend mode allowing different kind of effect.
  38687. */
  38688. get: function () {
  38689. return this._vignetteBlendMode;
  38690. },
  38691. /**
  38692. * Sets the vignette blend mode allowing different kind of effect.
  38693. */
  38694. set: function (value) {
  38695. if (this._vignetteBlendMode === value) {
  38696. return;
  38697. }
  38698. this._vignetteBlendMode = value;
  38699. this._updateParameters();
  38700. },
  38701. enumerable: true,
  38702. configurable: true
  38703. });
  38704. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  38705. /**
  38706. * Gets wether the vignette effect is enabled.
  38707. */
  38708. get: function () {
  38709. return this._vignetteEnabled;
  38710. },
  38711. /**
  38712. * Sets wether the vignette effect is enabled.
  38713. */
  38714. set: function (value) {
  38715. if (this._vignetteEnabled === value) {
  38716. return;
  38717. }
  38718. this._vignetteEnabled = value;
  38719. this._updateParameters();
  38720. },
  38721. enumerable: true,
  38722. configurable: true
  38723. });
  38724. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  38725. /**
  38726. * Gets wether the image processing is applied through a post process or not.
  38727. */
  38728. get: function () {
  38729. return this._applyByPostProcess;
  38730. },
  38731. /**
  38732. * Sets wether the image processing is applied through a post process or not.
  38733. */
  38734. set: function (value) {
  38735. if (this._applyByPostProcess === value) {
  38736. return;
  38737. }
  38738. this._applyByPostProcess = value;
  38739. this._updateParameters();
  38740. },
  38741. enumerable: true,
  38742. configurable: true
  38743. });
  38744. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  38745. /**
  38746. * Gets wether the image processing is enabled or not.
  38747. */
  38748. get: function () {
  38749. return this._isEnabled;
  38750. },
  38751. /**
  38752. * Sets wether the image processing is enabled or not.
  38753. */
  38754. set: function (value) {
  38755. if (this._isEnabled === value) {
  38756. return;
  38757. }
  38758. this._isEnabled = value;
  38759. this._updateParameters();
  38760. },
  38761. enumerable: true,
  38762. configurable: true
  38763. });
  38764. /**
  38765. * Method called each time the image processing information changes requires to recompile the effect.
  38766. */
  38767. ImageProcessingConfiguration.prototype._updateParameters = function () {
  38768. this.onUpdateParameters.notifyObservers(this);
  38769. };
  38770. ImageProcessingConfiguration.prototype.getClassName = function () {
  38771. return "ImageProcessingConfiguration";
  38772. };
  38773. /**
  38774. * Prepare the list of uniforms associated with the Image Processing effects.
  38775. * @param uniformsList The list of uniforms used in the effect
  38776. * @param defines the list of defines currently in use
  38777. */
  38778. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  38779. if (defines.EXPOSURE) {
  38780. uniforms.push("exposureLinear");
  38781. }
  38782. if (defines.CONTRAST) {
  38783. uniforms.push("contrast");
  38784. }
  38785. if (defines.COLORGRADING) {
  38786. uniforms.push("colorTransformSettings");
  38787. }
  38788. if (defines.VIGNETTE) {
  38789. uniforms.push("vInverseScreenSize");
  38790. uniforms.push("vignetteSettings1");
  38791. uniforms.push("vignetteSettings2");
  38792. }
  38793. if (defines.COLORCURVES) {
  38794. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  38795. }
  38796. };
  38797. /**
  38798. * Prepare the list of samplers associated with the Image Processing effects.
  38799. * @param uniformsList The list of uniforms used in the effect
  38800. * @param defines the list of defines currently in use
  38801. */
  38802. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  38803. if (defines.COLORGRADING) {
  38804. samplersList.push("txColorTransform");
  38805. }
  38806. };
  38807. /**
  38808. * Prepare the list of defines associated to the shader.
  38809. * @param defines the list of defines to complete
  38810. */
  38811. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  38812. if (forPostProcess === void 0) { forPostProcess = false; }
  38813. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  38814. defines.VIGNETTE = false;
  38815. defines.TONEMAPPING = false;
  38816. defines.CONTRAST = false;
  38817. defines.EXPOSURE = false;
  38818. defines.COLORCURVES = false;
  38819. defines.COLORGRADING = false;
  38820. defines.COLORGRADING3D = false;
  38821. defines.IMAGEPROCESSING = false;
  38822. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  38823. return;
  38824. }
  38825. defines.VIGNETTE = this.vignetteEnabled;
  38826. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  38827. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  38828. defines.TONEMAPPING = this.toneMappingEnabled;
  38829. defines.CONTRAST = (this.contrast !== 1.0);
  38830. defines.EXPOSURE = (this.exposure !== 1.0);
  38831. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  38832. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  38833. if (defines.COLORGRADING) {
  38834. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  38835. }
  38836. else {
  38837. defines.COLORGRADING3D = false;
  38838. }
  38839. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  38840. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  38841. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  38842. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  38843. };
  38844. /**
  38845. * Returns true if all the image processing information are ready.
  38846. */
  38847. ImageProcessingConfiguration.prototype.isReady = function () {
  38848. // Color Grading texure can not be none blocking.
  38849. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  38850. };
  38851. /**
  38852. * Binds the image processing to the shader.
  38853. * @param effect The effect to bind to
  38854. */
  38855. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  38856. if (aspectRatio === void 0) { aspectRatio = 1; }
  38857. // Color Curves
  38858. if (this._colorCurvesEnabled && this.colorCurves) {
  38859. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  38860. }
  38861. // Vignette
  38862. if (this._vignetteEnabled) {
  38863. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  38864. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  38865. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  38866. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  38867. var vignetteScaleX = vignetteScaleY * aspectRatio;
  38868. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  38869. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  38870. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  38871. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  38872. var vignettePower = -2.0 * this.vignetteWeight;
  38873. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  38874. }
  38875. // Exposure
  38876. effect.setFloat("exposureLinear", this.exposure);
  38877. // Contrast
  38878. effect.setFloat("contrast", this.contrast);
  38879. // Color transform settings
  38880. if (this.colorGradingTexture) {
  38881. effect.setTexture("txColorTransform", this.colorGradingTexture);
  38882. var textureSize = this.colorGradingTexture.getSize().height;
  38883. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  38884. 0.5 / textureSize, // textureOffset
  38885. textureSize, // textureSize
  38886. this.colorGradingTexture.level // weight
  38887. );
  38888. }
  38889. };
  38890. /**
  38891. * Clones the current image processing instance.
  38892. * @return The cloned image processing
  38893. */
  38894. ImageProcessingConfiguration.prototype.clone = function () {
  38895. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  38896. };
  38897. /**
  38898. * Serializes the current image processing instance to a json representation.
  38899. * @return a JSON representation
  38900. */
  38901. ImageProcessingConfiguration.prototype.serialize = function () {
  38902. return BABYLON.SerializationHelper.Serialize(this);
  38903. };
  38904. /**
  38905. * Parses the image processing from a json representation.
  38906. * @param source the JSON source to parse
  38907. * @return The parsed image processing
  38908. */
  38909. ImageProcessingConfiguration.Parse = function (source) {
  38910. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  38911. };
  38912. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  38913. /**
  38914. * Used to apply the vignette as a mix with the pixel color.
  38915. */
  38916. get: function () {
  38917. return this._VIGNETTEMODE_MULTIPLY;
  38918. },
  38919. enumerable: true,
  38920. configurable: true
  38921. });
  38922. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  38923. /**
  38924. * Used to apply the vignette as a replacement of the pixel color.
  38925. */
  38926. get: function () {
  38927. return this._VIGNETTEMODE_OPAQUE;
  38928. },
  38929. enumerable: true,
  38930. configurable: true
  38931. });
  38932. // Static constants associated to the image processing.
  38933. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  38934. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  38935. __decorate([
  38936. BABYLON.serializeAsColorCurves()
  38937. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  38938. __decorate([
  38939. BABYLON.serialize()
  38940. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  38941. __decorate([
  38942. BABYLON.serializeAsTexture()
  38943. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  38944. __decorate([
  38945. BABYLON.serialize()
  38946. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  38947. __decorate([
  38948. BABYLON.serialize()
  38949. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  38950. __decorate([
  38951. BABYLON.serialize()
  38952. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  38953. __decorate([
  38954. BABYLON.serialize()
  38955. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  38956. __decorate([
  38957. BABYLON.serialize()
  38958. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38959. __decorate([
  38960. BABYLON.serialize()
  38961. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38962. __decorate([
  38963. BABYLON.serialize()
  38964. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38965. __decorate([
  38966. BABYLON.serialize()
  38967. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38968. __decorate([
  38969. BABYLON.serialize()
  38970. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38971. __decorate([
  38972. BABYLON.serialize()
  38973. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38974. __decorate([
  38975. BABYLON.serializeAsColor4()
  38976. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38977. __decorate([
  38978. BABYLON.serialize()
  38979. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38980. __decorate([
  38981. BABYLON.serialize()
  38982. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38983. __decorate([
  38984. BABYLON.serialize()
  38985. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38986. __decorate([
  38987. BABYLON.serialize()
  38988. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38989. __decorate([
  38990. BABYLON.serialize()
  38991. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38992. return ImageProcessingConfiguration;
  38993. }());
  38994. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38995. })(BABYLON || (BABYLON = {}));
  38996. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38997. "use strict";
  38998. var BABYLON;
  38999. (function (BABYLON) {
  39000. /**
  39001. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  39002. * It can help converting any input color in a desired output one. This can then be used to create effects
  39003. * from sepia, black and white to sixties or futuristic rendering...
  39004. *
  39005. * The only supported format is currently 3dl.
  39006. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  39007. */
  39008. var ColorGradingTexture = /** @class */ (function (_super) {
  39009. __extends(ColorGradingTexture, _super);
  39010. /**
  39011. * Instantiates a ColorGradingTexture from the following parameters.
  39012. *
  39013. * @param url The location of the color gradind data (currently only supporting 3dl)
  39014. * @param scene The scene the texture will be used in
  39015. */
  39016. function ColorGradingTexture(url, scene) {
  39017. var _this = _super.call(this, scene) || this;
  39018. if (!url) {
  39019. return _this;
  39020. }
  39021. _this._engine = scene.getEngine();
  39022. _this._textureMatrix = BABYLON.Matrix.Identity();
  39023. _this.name = url;
  39024. _this.url = url;
  39025. _this.hasAlpha = false;
  39026. _this.isCube = false;
  39027. _this.is3D = _this._engine.webGLVersion > 1;
  39028. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39029. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39030. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39031. _this.anisotropicFilteringLevel = 1;
  39032. _this._texture = _this._getFromCache(url, true);
  39033. if (!_this._texture) {
  39034. if (!scene.useDelayedTextureLoading) {
  39035. _this.loadTexture();
  39036. }
  39037. else {
  39038. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39039. }
  39040. }
  39041. return _this;
  39042. }
  39043. /**
  39044. * Returns the texture matrix used in most of the material.
  39045. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  39046. */
  39047. ColorGradingTexture.prototype.getTextureMatrix = function () {
  39048. return this._textureMatrix;
  39049. };
  39050. /**
  39051. * Occurs when the file being loaded is a .3dl LUT file.
  39052. */
  39053. ColorGradingTexture.prototype.load3dlTexture = function () {
  39054. var engine = this._engine;
  39055. var texture;
  39056. if (engine.webGLVersion === 1) {
  39057. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39058. }
  39059. else {
  39060. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39061. }
  39062. this._texture = texture;
  39063. var callback = function (text) {
  39064. if (typeof text !== "string") {
  39065. return;
  39066. }
  39067. var data = null;
  39068. var tempData = null;
  39069. var line;
  39070. var lines = text.split('\n');
  39071. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  39072. var maxColor = 0;
  39073. for (var i = 0; i < lines.length; i++) {
  39074. line = lines[i];
  39075. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  39076. continue;
  39077. if (line.indexOf('#') === 0)
  39078. continue;
  39079. var words = line.split(" ");
  39080. if (size === 0) {
  39081. // Number of space + one
  39082. size = words.length;
  39083. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  39084. tempData = new Float32Array(size * size * size * 4);
  39085. continue;
  39086. }
  39087. if (size != 0) {
  39088. var r = Math.max(parseInt(words[0]), 0);
  39089. var g = Math.max(parseInt(words[1]), 0);
  39090. var b = Math.max(parseInt(words[2]), 0);
  39091. maxColor = Math.max(r, maxColor);
  39092. maxColor = Math.max(g, maxColor);
  39093. maxColor = Math.max(b, maxColor);
  39094. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  39095. if (tempData) {
  39096. tempData[pixelStorageIndex + 0] = r;
  39097. tempData[pixelStorageIndex + 1] = g;
  39098. tempData[pixelStorageIndex + 2] = b;
  39099. }
  39100. pixelIndexSlice++;
  39101. if (pixelIndexSlice % size == 0) {
  39102. pixelIndexH++;
  39103. pixelIndexSlice = 0;
  39104. if (pixelIndexH % size == 0) {
  39105. pixelIndexW++;
  39106. pixelIndexH = 0;
  39107. }
  39108. }
  39109. }
  39110. }
  39111. if (tempData && data) {
  39112. for (var i = 0; i < tempData.length; i++) {
  39113. if (i > 0 && (i + 1) % 4 === 0) {
  39114. data[i] = 255;
  39115. }
  39116. else {
  39117. var value = tempData[i];
  39118. data[i] = (value / maxColor * 255);
  39119. }
  39120. }
  39121. }
  39122. if (texture.is3D) {
  39123. texture.updateSize(size, size, size);
  39124. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  39125. }
  39126. else {
  39127. texture.updateSize(size * size, size);
  39128. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  39129. }
  39130. };
  39131. var scene = this.getScene();
  39132. if (scene) {
  39133. scene._loadFile(this.url, callback);
  39134. }
  39135. else {
  39136. this._engine._loadFile(this.url, callback);
  39137. }
  39138. return this._texture;
  39139. };
  39140. /**
  39141. * Starts the loading process of the texture.
  39142. */
  39143. ColorGradingTexture.prototype.loadTexture = function () {
  39144. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  39145. this.load3dlTexture();
  39146. }
  39147. };
  39148. /**
  39149. * Clones the color gradind texture.
  39150. */
  39151. ColorGradingTexture.prototype.clone = function () {
  39152. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  39153. // Base texture
  39154. newTexture.level = this.level;
  39155. return newTexture;
  39156. };
  39157. /**
  39158. * Called during delayed load for textures.
  39159. */
  39160. ColorGradingTexture.prototype.delayLoad = function () {
  39161. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39162. return;
  39163. }
  39164. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39165. this._texture = this._getFromCache(this.url, true);
  39166. if (!this._texture) {
  39167. this.loadTexture();
  39168. }
  39169. };
  39170. /**
  39171. * Parses a color grading texture serialized by Babylon.
  39172. * @param parsedTexture The texture information being parsedTexture
  39173. * @param scene The scene to load the texture in
  39174. * @param rootUrl The root url of the data assets to load
  39175. * @return A color gradind texture
  39176. */
  39177. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39178. var texture = null;
  39179. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39180. texture = new ColorGradingTexture(parsedTexture.name, scene);
  39181. texture.name = parsedTexture.name;
  39182. texture.level = parsedTexture.level;
  39183. }
  39184. return texture;
  39185. };
  39186. /**
  39187. * Serializes the LUT texture to json format.
  39188. */
  39189. ColorGradingTexture.prototype.serialize = function () {
  39190. if (!this.name) {
  39191. return null;
  39192. }
  39193. var serializationObject = {};
  39194. serializationObject.name = this.name;
  39195. serializationObject.level = this.level;
  39196. serializationObject.customType = "BABYLON.ColorGradingTexture";
  39197. return serializationObject;
  39198. };
  39199. /**
  39200. * Empty line regex stored for GC.
  39201. */
  39202. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  39203. return ColorGradingTexture;
  39204. }(BABYLON.BaseTexture));
  39205. BABYLON.ColorGradingTexture = ColorGradingTexture;
  39206. })(BABYLON || (BABYLON = {}));
  39207. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  39208. "use strict";
  39209. var BABYLON;
  39210. (function (BABYLON) {
  39211. /**
  39212. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39213. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39214. * 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;
  39215. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39216. */
  39217. var ColorCurves = /** @class */ (function () {
  39218. function ColorCurves() {
  39219. this._dirty = true;
  39220. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  39221. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  39222. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39223. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  39224. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39225. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  39226. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  39227. this._globalHue = 30;
  39228. this._globalDensity = 0;
  39229. this._globalSaturation = 0;
  39230. this._globalExposure = 0;
  39231. this._highlightsHue = 30;
  39232. this._highlightsDensity = 0;
  39233. this._highlightsSaturation = 0;
  39234. this._highlightsExposure = 0;
  39235. this._midtonesHue = 30;
  39236. this._midtonesDensity = 0;
  39237. this._midtonesSaturation = 0;
  39238. this._midtonesExposure = 0;
  39239. this._shadowsHue = 30;
  39240. this._shadowsDensity = 0;
  39241. this._shadowsSaturation = 0;
  39242. this._shadowsExposure = 0;
  39243. }
  39244. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  39245. /**
  39246. * Gets the global Hue value.
  39247. * 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).
  39248. */
  39249. get: function () {
  39250. return this._globalHue;
  39251. },
  39252. /**
  39253. * Sets the global Hue value.
  39254. * 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).
  39255. */
  39256. set: function (value) {
  39257. this._globalHue = value;
  39258. this._dirty = true;
  39259. },
  39260. enumerable: true,
  39261. configurable: true
  39262. });
  39263. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  39264. /**
  39265. * Gets the global Density value.
  39266. * 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.
  39267. * Values less than zero provide a filter of opposite hue.
  39268. */
  39269. get: function () {
  39270. return this._globalDensity;
  39271. },
  39272. /**
  39273. * Sets the global Density value.
  39274. * 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.
  39275. * Values less than zero provide a filter of opposite hue.
  39276. */
  39277. set: function (value) {
  39278. this._globalDensity = value;
  39279. this._dirty = true;
  39280. },
  39281. enumerable: true,
  39282. configurable: true
  39283. });
  39284. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  39285. /**
  39286. * Gets the global Saturation value.
  39287. * 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.
  39288. */
  39289. get: function () {
  39290. return this._globalSaturation;
  39291. },
  39292. /**
  39293. * Sets the global Saturation value.
  39294. * 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.
  39295. */
  39296. set: function (value) {
  39297. this._globalSaturation = value;
  39298. this._dirty = true;
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  39304. /**
  39305. * Gets the highlights Hue value.
  39306. * 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).
  39307. */
  39308. get: function () {
  39309. return this._highlightsHue;
  39310. },
  39311. /**
  39312. * Sets the highlights Hue value.
  39313. * 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).
  39314. */
  39315. set: function (value) {
  39316. this._highlightsHue = value;
  39317. this._dirty = true;
  39318. },
  39319. enumerable: true,
  39320. configurable: true
  39321. });
  39322. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  39323. /**
  39324. * Gets the highlights Density value.
  39325. * 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.
  39326. * Values less than zero provide a filter of opposite hue.
  39327. */
  39328. get: function () {
  39329. return this._highlightsDensity;
  39330. },
  39331. /**
  39332. * Sets the highlights Density value.
  39333. * 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.
  39334. * Values less than zero provide a filter of opposite hue.
  39335. */
  39336. set: function (value) {
  39337. this._highlightsDensity = value;
  39338. this._dirty = true;
  39339. },
  39340. enumerable: true,
  39341. configurable: true
  39342. });
  39343. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  39344. /**
  39345. * Gets the highlights Saturation value.
  39346. * 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.
  39347. */
  39348. get: function () {
  39349. return this._highlightsSaturation;
  39350. },
  39351. /**
  39352. * Sets the highlights Saturation value.
  39353. * 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.
  39354. */
  39355. set: function (value) {
  39356. this._highlightsSaturation = value;
  39357. this._dirty = true;
  39358. },
  39359. enumerable: true,
  39360. configurable: true
  39361. });
  39362. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  39363. /**
  39364. * Gets the highlights Exposure value.
  39365. * 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.
  39366. */
  39367. get: function () {
  39368. return this._highlightsExposure;
  39369. },
  39370. /**
  39371. * Sets the highlights Exposure value.
  39372. * 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.
  39373. */
  39374. set: function (value) {
  39375. this._highlightsExposure = value;
  39376. this._dirty = true;
  39377. },
  39378. enumerable: true,
  39379. configurable: true
  39380. });
  39381. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  39382. /**
  39383. * Gets the midtones Hue value.
  39384. * 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).
  39385. */
  39386. get: function () {
  39387. return this._midtonesHue;
  39388. },
  39389. /**
  39390. * Sets the midtones Hue value.
  39391. * 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).
  39392. */
  39393. set: function (value) {
  39394. this._midtonesHue = value;
  39395. this._dirty = true;
  39396. },
  39397. enumerable: true,
  39398. configurable: true
  39399. });
  39400. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  39401. /**
  39402. * Gets the midtones Density value.
  39403. * 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.
  39404. * Values less than zero provide a filter of opposite hue.
  39405. */
  39406. get: function () {
  39407. return this._midtonesDensity;
  39408. },
  39409. /**
  39410. * Sets the midtones Density value.
  39411. * 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.
  39412. * Values less than zero provide a filter of opposite hue.
  39413. */
  39414. set: function (value) {
  39415. this._midtonesDensity = value;
  39416. this._dirty = true;
  39417. },
  39418. enumerable: true,
  39419. configurable: true
  39420. });
  39421. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  39422. /**
  39423. * Gets the midtones Saturation value.
  39424. * 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.
  39425. */
  39426. get: function () {
  39427. return this._midtonesSaturation;
  39428. },
  39429. /**
  39430. * Sets the midtones Saturation value.
  39431. * 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.
  39432. */
  39433. set: function (value) {
  39434. this._midtonesSaturation = value;
  39435. this._dirty = true;
  39436. },
  39437. enumerable: true,
  39438. configurable: true
  39439. });
  39440. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  39441. /**
  39442. * Gets the midtones Exposure value.
  39443. * 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.
  39444. */
  39445. get: function () {
  39446. return this._midtonesExposure;
  39447. },
  39448. /**
  39449. * Sets the midtones Exposure value.
  39450. * 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.
  39451. */
  39452. set: function (value) {
  39453. this._midtonesExposure = value;
  39454. this._dirty = true;
  39455. },
  39456. enumerable: true,
  39457. configurable: true
  39458. });
  39459. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  39460. /**
  39461. * Gets the shadows Hue value.
  39462. * 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).
  39463. */
  39464. get: function () {
  39465. return this._shadowsHue;
  39466. },
  39467. /**
  39468. * Sets the shadows Hue value.
  39469. * 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).
  39470. */
  39471. set: function (value) {
  39472. this._shadowsHue = value;
  39473. this._dirty = true;
  39474. },
  39475. enumerable: true,
  39476. configurable: true
  39477. });
  39478. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  39479. /**
  39480. * Gets the shadows Density value.
  39481. * 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.
  39482. * Values less than zero provide a filter of opposite hue.
  39483. */
  39484. get: function () {
  39485. return this._shadowsDensity;
  39486. },
  39487. /**
  39488. * Sets the shadows Density value.
  39489. * 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.
  39490. * Values less than zero provide a filter of opposite hue.
  39491. */
  39492. set: function (value) {
  39493. this._shadowsDensity = value;
  39494. this._dirty = true;
  39495. },
  39496. enumerable: true,
  39497. configurable: true
  39498. });
  39499. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  39500. /**
  39501. * Gets the shadows Saturation value.
  39502. * 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.
  39503. */
  39504. get: function () {
  39505. return this._shadowsSaturation;
  39506. },
  39507. /**
  39508. * Sets the shadows Saturation value.
  39509. * 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.
  39510. */
  39511. set: function (value) {
  39512. this._shadowsSaturation = value;
  39513. this._dirty = true;
  39514. },
  39515. enumerable: true,
  39516. configurable: true
  39517. });
  39518. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  39519. /**
  39520. * Gets the shadows Exposure value.
  39521. * 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.
  39522. */
  39523. get: function () {
  39524. return this._shadowsExposure;
  39525. },
  39526. /**
  39527. * Sets the shadows Exposure value.
  39528. * 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.
  39529. */
  39530. set: function (value) {
  39531. this._shadowsExposure = value;
  39532. this._dirty = true;
  39533. },
  39534. enumerable: true,
  39535. configurable: true
  39536. });
  39537. ColorCurves.prototype.getClassName = function () {
  39538. return "ColorCurves";
  39539. };
  39540. /**
  39541. * Binds the color curves to the shader.
  39542. * @param colorCurves The color curve to bind
  39543. * @param effect The effect to bind to
  39544. */
  39545. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  39546. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  39547. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  39548. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  39549. if (colorCurves._dirty) {
  39550. colorCurves._dirty = false;
  39551. // Fill in global info.
  39552. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  39553. // Compute highlights info.
  39554. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  39555. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  39556. // Compute midtones info.
  39557. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  39558. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  39559. // Compute shadows info.
  39560. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  39561. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  39562. // Compute deltas (neutral is midtones).
  39563. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  39564. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  39565. }
  39566. if (effect) {
  39567. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  39568. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  39569. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  39570. }
  39571. };
  39572. /**
  39573. * Prepare the list of uniforms associated with the ColorCurves effects.
  39574. * @param uniformsList The list of uniforms used in the effect
  39575. */
  39576. ColorCurves.PrepareUniforms = function (uniformsList) {
  39577. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  39578. };
  39579. /**
  39580. * Returns color grading data based on a hue, density, saturation and exposure value.
  39581. * @param filterHue The hue of the color filter.
  39582. * @param filterDensity The density of the color filter.
  39583. * @param saturation The saturation.
  39584. * @param exposure The exposure.
  39585. * @param result The result data container.
  39586. */
  39587. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  39588. if (hue == null) {
  39589. return;
  39590. }
  39591. hue = ColorCurves.clamp(hue, 0, 360);
  39592. density = ColorCurves.clamp(density, -100, 100);
  39593. saturation = ColorCurves.clamp(saturation, -100, 100);
  39594. exposure = ColorCurves.clamp(exposure, -100, 100);
  39595. // Remap the slider/config filter density with non-linear mapping and also scale by half
  39596. // so that the maximum filter density is only 50% control. This provides fine control
  39597. // for small values and reasonable range.
  39598. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  39599. density *= 0.5;
  39600. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  39601. if (density < 0) {
  39602. density *= -1;
  39603. hue = (hue + 180) % 360;
  39604. }
  39605. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  39606. result.scaleToRef(2, result);
  39607. result.a = 1 + 0.01 * saturation;
  39608. };
  39609. /**
  39610. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  39611. * @param value The input slider value in range [-100,100].
  39612. * @returns Adjusted value.
  39613. */
  39614. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  39615. value /= 100;
  39616. var x = Math.abs(value);
  39617. x = Math.pow(x, 2);
  39618. if (value < 0) {
  39619. x *= -1;
  39620. }
  39621. x *= 100;
  39622. return x;
  39623. };
  39624. /**
  39625. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  39626. * @param hue The hue (H) input.
  39627. * @param saturation The saturation (S) input.
  39628. * @param brightness The brightness (B) input.
  39629. * @result An RGBA color represented as Vector4.
  39630. */
  39631. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  39632. var h = ColorCurves.clamp(hue, 0, 360);
  39633. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  39634. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  39635. if (s === 0) {
  39636. result.r = v;
  39637. result.g = v;
  39638. result.b = v;
  39639. }
  39640. else {
  39641. // sector 0 to 5
  39642. h /= 60;
  39643. var i = Math.floor(h);
  39644. // fractional part of h
  39645. var f = h - i;
  39646. var p = v * (1 - s);
  39647. var q = v * (1 - s * f);
  39648. var t = v * (1 - s * (1 - f));
  39649. switch (i) {
  39650. case 0:
  39651. result.r = v;
  39652. result.g = t;
  39653. result.b = p;
  39654. break;
  39655. case 1:
  39656. result.r = q;
  39657. result.g = v;
  39658. result.b = p;
  39659. break;
  39660. case 2:
  39661. result.r = p;
  39662. result.g = v;
  39663. result.b = t;
  39664. break;
  39665. case 3:
  39666. result.r = p;
  39667. result.g = q;
  39668. result.b = v;
  39669. break;
  39670. case 4:
  39671. result.r = t;
  39672. result.g = p;
  39673. result.b = v;
  39674. break;
  39675. default:// case 5:
  39676. result.r = v;
  39677. result.g = p;
  39678. result.b = q;
  39679. break;
  39680. }
  39681. }
  39682. result.a = 1;
  39683. };
  39684. /**
  39685. * Returns a value clamped between min and max
  39686. * @param value The value to clamp
  39687. * @param min The minimum of value
  39688. * @param max The maximum of value
  39689. * @returns The clamped value.
  39690. */
  39691. ColorCurves.clamp = function (value, min, max) {
  39692. return Math.min(Math.max(value, min), max);
  39693. };
  39694. /**
  39695. * Clones the current color curve instance.
  39696. * @return The cloned curves
  39697. */
  39698. ColorCurves.prototype.clone = function () {
  39699. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  39700. };
  39701. /**
  39702. * Serializes the current color curve instance to a json representation.
  39703. * @return a JSON representation
  39704. */
  39705. ColorCurves.prototype.serialize = function () {
  39706. return BABYLON.SerializationHelper.Serialize(this);
  39707. };
  39708. /**
  39709. * Parses the color curve from a json representation.
  39710. * @param source the JSON source to parse
  39711. * @return The parsed curves
  39712. */
  39713. ColorCurves.Parse = function (source) {
  39714. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  39715. };
  39716. __decorate([
  39717. BABYLON.serialize()
  39718. ], ColorCurves.prototype, "_globalHue", void 0);
  39719. __decorate([
  39720. BABYLON.serialize()
  39721. ], ColorCurves.prototype, "_globalDensity", void 0);
  39722. __decorate([
  39723. BABYLON.serialize()
  39724. ], ColorCurves.prototype, "_globalSaturation", void 0);
  39725. __decorate([
  39726. BABYLON.serialize()
  39727. ], ColorCurves.prototype, "_globalExposure", void 0);
  39728. __decorate([
  39729. BABYLON.serialize()
  39730. ], ColorCurves.prototype, "_highlightsHue", void 0);
  39731. __decorate([
  39732. BABYLON.serialize()
  39733. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  39734. __decorate([
  39735. BABYLON.serialize()
  39736. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  39737. __decorate([
  39738. BABYLON.serialize()
  39739. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  39740. __decorate([
  39741. BABYLON.serialize()
  39742. ], ColorCurves.prototype, "_midtonesHue", void 0);
  39743. __decorate([
  39744. BABYLON.serialize()
  39745. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  39746. __decorate([
  39747. BABYLON.serialize()
  39748. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  39749. __decorate([
  39750. BABYLON.serialize()
  39751. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  39752. return ColorCurves;
  39753. }());
  39754. BABYLON.ColorCurves = ColorCurves;
  39755. })(BABYLON || (BABYLON = {}));
  39756. //# sourceMappingURL=babylon.colorCurves.js.map
  39757. "use strict";
  39758. //# sourceMappingURL=babylon.behavior.js.map
  39759. "use strict";
  39760. var BABYLON;
  39761. (function (BABYLON) {
  39762. /**
  39763. * "Static Class" containing the most commonly used helper while dealing with material for
  39764. * rendering purpose.
  39765. *
  39766. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  39767. *
  39768. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  39769. */
  39770. var MaterialHelper = /** @class */ (function () {
  39771. function MaterialHelper() {
  39772. }
  39773. /**
  39774. * Bind the current view position to an effect.
  39775. * @param effect The effect to be bound
  39776. * @param scene The scene the eyes position is used from
  39777. */
  39778. MaterialHelper.BindEyePosition = function (effect, scene) {
  39779. if (scene._forcedViewPosition) {
  39780. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  39781. return;
  39782. }
  39783. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39784. };
  39785. /**
  39786. * Helps preparing the defines values about the UVs in used in the effect.
  39787. * UVs are shared as much as we can accross chanels in the shaders.
  39788. * @param texture The texture we are preparing the UVs for
  39789. * @param defines The defines to update
  39790. * @param key The chanel key "diffuse", "specular"... used in the shader
  39791. */
  39792. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  39793. defines._needUVs = true;
  39794. defines[key] = true;
  39795. if (texture.getTextureMatrix().isIdentity(true)) {
  39796. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  39797. if (texture.coordinatesIndex === 0) {
  39798. defines["MAINUV1"] = true;
  39799. }
  39800. else {
  39801. defines["MAINUV2"] = true;
  39802. }
  39803. }
  39804. else {
  39805. defines[key + "DIRECTUV"] = 0;
  39806. }
  39807. };
  39808. /**
  39809. * Binds a texture matrix value to its corrsponding uniform
  39810. * @param texture The texture to bind the matrix for
  39811. * @param uniformBuffer The uniform buffer receivin the data
  39812. * @param key The chanel key "diffuse", "specular"... used in the shader
  39813. */
  39814. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  39815. var matrix = texture.getTextureMatrix();
  39816. if (!matrix.isIdentity(true)) {
  39817. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  39818. }
  39819. };
  39820. /**
  39821. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  39822. * @param mesh defines the current mesh
  39823. * @param scene defines the current scene
  39824. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  39825. * @param pointsCloud defines if point cloud rendering has to be turned on
  39826. * @param fogEnabled defines if fog has to be turned on
  39827. * @param alphaTest defines if alpha testing has to be turned on
  39828. * @param defines defines the current list of defines
  39829. */
  39830. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  39831. if (defines._areMiscDirty) {
  39832. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  39833. defines["POINTSIZE"] = pointsCloud;
  39834. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  39835. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  39836. defines["ALPHATEST"] = alphaTest;
  39837. }
  39838. };
  39839. /**
  39840. * Helper used to prepare the list of defines associated with frame values for shader compilation
  39841. * @param scene defines the current scene
  39842. * @param engine defines the current engine
  39843. * @param defines specifies the list of active defines
  39844. * @param useInstances defines if instances have to be turned on
  39845. * @param useClipPlane defines if clip plane have to be turned on
  39846. */
  39847. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  39848. if (useClipPlane === void 0) { useClipPlane = null; }
  39849. var changed = false;
  39850. if (useClipPlane == null) {
  39851. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  39852. }
  39853. if (defines["CLIPPLANE"] !== useClipPlane) {
  39854. defines["CLIPPLANE"] = useClipPlane;
  39855. changed = true;
  39856. }
  39857. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  39858. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  39859. changed = true;
  39860. }
  39861. if (defines["INSTANCES"] !== useInstances) {
  39862. defines["INSTANCES"] = useInstances;
  39863. changed = true;
  39864. }
  39865. if (changed) {
  39866. defines.markAsUnprocessed();
  39867. }
  39868. };
  39869. /**
  39870. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  39871. * @param mesh The mesh containing the geometry data we will draw
  39872. * @param defines The defines to update
  39873. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  39874. * @param useBones Precise whether bones should be used or not (override mesh info)
  39875. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  39876. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  39877. * @returns false if defines are considered not dirty and have not been checked
  39878. */
  39879. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  39880. if (useMorphTargets === void 0) { useMorphTargets = false; }
  39881. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  39882. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  39883. return false;
  39884. }
  39885. defines._normals = defines._needNormals;
  39886. defines._uvs = defines._needUVs;
  39887. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  39888. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39889. defines["TANGENT"] = true;
  39890. }
  39891. if (defines._needUVs) {
  39892. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  39893. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  39894. }
  39895. else {
  39896. defines["UV1"] = false;
  39897. defines["UV2"] = false;
  39898. }
  39899. if (useVertexColor) {
  39900. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  39901. defines["VERTEXCOLOR"] = hasVertexColors;
  39902. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  39903. }
  39904. if (useBones) {
  39905. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39906. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  39907. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  39908. }
  39909. else {
  39910. defines["NUM_BONE_INFLUENCERS"] = 0;
  39911. defines["BonesPerMesh"] = 0;
  39912. }
  39913. }
  39914. if (useMorphTargets) {
  39915. var manager = mesh.morphTargetManager;
  39916. if (manager) {
  39917. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  39918. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  39919. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  39920. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  39921. }
  39922. else {
  39923. defines["MORPHTARGETS_TANGENT"] = false;
  39924. defines["MORPHTARGETS_NORMAL"] = false;
  39925. defines["MORPHTARGETS"] = false;
  39926. defines["NUM_MORPH_INFLUENCERS"] = 0;
  39927. }
  39928. }
  39929. return true;
  39930. };
  39931. /**
  39932. * Prepares the defines related to the light information passed in parameter
  39933. * @param scene The scene we are intending to draw
  39934. * @param mesh The mesh the effect is compiling for
  39935. * @param defines The defines to update
  39936. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  39937. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  39938. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  39939. * @returns true if normals will be required for the rest of the effect
  39940. */
  39941. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  39942. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39943. if (disableLighting === void 0) { disableLighting = false; }
  39944. if (!defines._areLightsDirty) {
  39945. return defines._needNormals;
  39946. }
  39947. var lightIndex = 0;
  39948. var needNormals = false;
  39949. var needRebuild = false;
  39950. var lightmapMode = false;
  39951. var shadowEnabled = false;
  39952. var specularEnabled = false;
  39953. if (scene.lightsEnabled && !disableLighting) {
  39954. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39955. var light = _a[_i];
  39956. needNormals = true;
  39957. if (defines["LIGHT" + lightIndex] === undefined) {
  39958. needRebuild = true;
  39959. }
  39960. defines["LIGHT" + lightIndex] = true;
  39961. defines["SPOTLIGHT" + lightIndex] = false;
  39962. defines["HEMILIGHT" + lightIndex] = false;
  39963. defines["POINTLIGHT" + lightIndex] = false;
  39964. defines["DIRLIGHT" + lightIndex] = false;
  39965. var type;
  39966. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39967. type = "SPOTLIGHT" + lightIndex;
  39968. var spotLight = light;
  39969. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39970. }
  39971. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39972. type = "HEMILIGHT" + lightIndex;
  39973. }
  39974. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39975. type = "POINTLIGHT" + lightIndex;
  39976. }
  39977. else {
  39978. type = "DIRLIGHT" + lightIndex;
  39979. }
  39980. defines[type] = true;
  39981. // Specular
  39982. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39983. specularEnabled = true;
  39984. }
  39985. // Shadows
  39986. defines["SHADOW" + lightIndex] = false;
  39987. defines["SHADOWPCF" + lightIndex] = false;
  39988. defines["SHADOWPCSS" + lightIndex] = false;
  39989. defines["SHADOWPOISSON" + lightIndex] = false;
  39990. defines["SHADOWESM" + lightIndex] = false;
  39991. defines["SHADOWCUBE" + lightIndex] = false;
  39992. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39993. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39994. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39995. var shadowGenerator = light.getShadowGenerator();
  39996. if (shadowGenerator) {
  39997. shadowEnabled = true;
  39998. shadowGenerator.prepareDefines(defines, lightIndex);
  39999. }
  40000. }
  40001. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40002. lightmapMode = true;
  40003. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40004. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40005. }
  40006. else {
  40007. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40008. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40009. }
  40010. lightIndex++;
  40011. if (lightIndex === maxSimultaneousLights)
  40012. break;
  40013. }
  40014. }
  40015. defines["SPECULARTERM"] = specularEnabled;
  40016. defines["SHADOWS"] = shadowEnabled;
  40017. // Resetting all other lights if any
  40018. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40019. if (defines["LIGHT" + index] !== undefined) {
  40020. defines["LIGHT" + index] = false;
  40021. defines["HEMILIGHT" + lightIndex] = false;
  40022. defines["POINTLIGHT" + lightIndex] = false;
  40023. defines["DIRLIGHT" + lightIndex] = false;
  40024. defines["SPOTLIGHT" + lightIndex] = false;
  40025. defines["SHADOW" + lightIndex] = false;
  40026. }
  40027. }
  40028. var caps = scene.getEngine().getCaps();
  40029. if (defines["SHADOWFLOAT"] === undefined) {
  40030. needRebuild = true;
  40031. }
  40032. defines["SHADOWFLOAT"] = shadowEnabled &&
  40033. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40034. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40035. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40036. if (needRebuild) {
  40037. defines.rebuild();
  40038. }
  40039. return needNormals;
  40040. };
  40041. /**
  40042. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40043. * that won t be acctive due to defines being turned off.
  40044. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40045. * @param samplersList The samplers list
  40046. * @param defines The defines helping in the list generation
  40047. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40048. */
  40049. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40050. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40051. var uniformsList;
  40052. var uniformBuffersList = null;
  40053. if (uniformsListOrOptions.uniformsNames) {
  40054. var options = uniformsListOrOptions;
  40055. uniformsList = options.uniformsNames;
  40056. uniformBuffersList = options.uniformBuffersNames;
  40057. samplersList = options.samplers;
  40058. defines = options.defines;
  40059. maxSimultaneousLights = options.maxSimultaneousLights;
  40060. }
  40061. else {
  40062. uniformsList = uniformsListOrOptions;
  40063. if (!samplersList) {
  40064. samplersList = [];
  40065. }
  40066. }
  40067. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40068. if (!defines["LIGHT" + lightIndex]) {
  40069. break;
  40070. }
  40071. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40072. if (uniformBuffersList) {
  40073. uniformBuffersList.push("Light" + lightIndex);
  40074. }
  40075. samplersList.push("shadowSampler" + lightIndex);
  40076. samplersList.push("depthSampler" + lightIndex);
  40077. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40078. samplersList.push("projectionLightSampler" + lightIndex);
  40079. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40080. }
  40081. }
  40082. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40083. uniformsList.push("morphTargetInfluences");
  40084. }
  40085. };
  40086. /**
  40087. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40088. * @param defines The defines to update while falling back
  40089. * @param fallbacks The authorized effect fallbacks
  40090. * @param maxSimultaneousLights The maximum number of lights allowed
  40091. * @param rank the current rank of the Effect
  40092. * @returns The newly affected rank
  40093. */
  40094. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40095. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40096. if (rank === void 0) { rank = 0; }
  40097. var lightFallbackRank = 0;
  40098. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40099. if (!defines["LIGHT" + lightIndex]) {
  40100. break;
  40101. }
  40102. if (lightIndex > 0) {
  40103. lightFallbackRank = rank + lightIndex;
  40104. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40105. }
  40106. if (!defines["SHADOWS"]) {
  40107. if (defines["SHADOW" + lightIndex]) {
  40108. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40109. }
  40110. if (defines["SHADOWPCF" + lightIndex]) {
  40111. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40112. }
  40113. if (defines["SHADOWPCSS" + lightIndex]) {
  40114. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40115. }
  40116. if (defines["SHADOWPOISSON" + lightIndex]) {
  40117. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40118. }
  40119. if (defines["SHADOWESM" + lightIndex]) {
  40120. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40121. }
  40122. }
  40123. }
  40124. return lightFallbackRank++;
  40125. };
  40126. /**
  40127. * Prepares the list of attributes required for morph targets according to the effect defines.
  40128. * @param attribs The current list of supported attribs
  40129. * @param mesh The mesh to prepare the morph targets attributes for
  40130. * @param defines The current Defines of the effect
  40131. */
  40132. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40133. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40134. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40135. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40136. var manager = mesh.morphTargetManager;
  40137. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40138. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40139. for (var index = 0; index < influencers; index++) {
  40140. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40141. if (normal) {
  40142. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40143. }
  40144. if (tangent) {
  40145. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40146. }
  40147. if (attribs.length > maxAttributesCount) {
  40148. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40149. }
  40150. }
  40151. }
  40152. };
  40153. /**
  40154. * Prepares the list of attributes required for bones according to the effect defines.
  40155. * @param attribs The current list of supported attribs
  40156. * @param mesh The mesh to prepare the bones attributes for
  40157. * @param defines The current Defines of the effect
  40158. * @param fallbacks The current efffect fallback strategy
  40159. */
  40160. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40161. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40162. fallbacks.addCPUSkinningFallback(0, mesh);
  40163. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40164. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40165. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40166. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40167. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40168. }
  40169. }
  40170. };
  40171. /**
  40172. * Prepares the list of attributes required for instances according to the effect defines.
  40173. * @param attribs The current list of supported attribs
  40174. * @param defines The current Defines of the effect
  40175. */
  40176. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  40177. if (defines["INSTANCES"]) {
  40178. attribs.push("world0");
  40179. attribs.push("world1");
  40180. attribs.push("world2");
  40181. attribs.push("world3");
  40182. }
  40183. };
  40184. /**
  40185. * Binds the light shadow information to the effect for the given mesh.
  40186. * @param light The light containing the generator
  40187. * @param scene The scene the lights belongs to
  40188. * @param mesh The mesh we are binding the information to render
  40189. * @param lightIndex The light index in the effect used to render the mesh
  40190. * @param effect The effect we are binding the data to
  40191. */
  40192. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  40193. if (light.shadowEnabled && mesh.receiveShadows) {
  40194. var shadowGenerator = light.getShadowGenerator();
  40195. if (shadowGenerator) {
  40196. shadowGenerator.bindShadowLight(lightIndex, effect);
  40197. }
  40198. }
  40199. };
  40200. /**
  40201. * Binds the light information to the effect.
  40202. * @param light The light containing the generator
  40203. * @param effect The effect we are binding the data to
  40204. * @param lightIndex The light index in the effect used to render
  40205. */
  40206. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  40207. light.transferToEffect(effect, lightIndex + "");
  40208. };
  40209. /**
  40210. * Binds the lights information from the scene to the effect for the given mesh.
  40211. * @param scene The scene the lights belongs to
  40212. * @param mesh The mesh we are binding the information to render
  40213. * @param effect The effect we are binding the data to
  40214. * @param defines The generated defines for the effect
  40215. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  40216. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  40217. */
  40218. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  40219. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40220. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  40221. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  40222. for (var i = 0; i < len; i++) {
  40223. var light = mesh._lightSources[i];
  40224. var iAsString = i.toString();
  40225. var scaledIntensity = light.getScaledIntensity();
  40226. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  40227. MaterialHelper.BindLightProperties(light, effect, i);
  40228. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  40229. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  40230. if (defines["SPECULARTERM"]) {
  40231. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  40232. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  40233. }
  40234. // Shadows
  40235. if (scene.shadowsEnabled) {
  40236. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  40237. }
  40238. light._uniformBuffer.update();
  40239. }
  40240. };
  40241. /**
  40242. * Binds the fog information from the scene to the effect for the given mesh.
  40243. * @param scene The scene the lights belongs to
  40244. * @param mesh The mesh we are binding the information to render
  40245. * @param effect The effect we are binding the data to
  40246. */
  40247. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  40248. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  40249. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  40250. effect.setColor3("vFogColor", scene.fogColor);
  40251. }
  40252. };
  40253. /**
  40254. * Binds the bones information from the mesh to the effect.
  40255. * @param mesh The mesh we are binding the information to render
  40256. * @param effect The effect we are binding the data to
  40257. */
  40258. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  40259. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40260. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  40261. if (matrices && effect) {
  40262. effect.setMatrices("mBones", matrices);
  40263. }
  40264. }
  40265. };
  40266. /**
  40267. * Binds the morph targets information from the mesh to the effect.
  40268. * @param abstractMesh The mesh we are binding the information to render
  40269. * @param effect The effect we are binding the data to
  40270. */
  40271. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  40272. var manager = abstractMesh.morphTargetManager;
  40273. if (!abstractMesh || !manager) {
  40274. return;
  40275. }
  40276. effect.setFloatArray("morphTargetInfluences", manager.influences);
  40277. };
  40278. /**
  40279. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  40280. * @param defines The generated defines used in the effect
  40281. * @param effect The effect we are binding the data to
  40282. * @param scene The scene we are willing to render with logarithmic scale for
  40283. */
  40284. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  40285. if (defines["LOGARITHMICDEPTH"]) {
  40286. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  40287. }
  40288. };
  40289. /**
  40290. * Binds the clip plane information from the scene to the effect.
  40291. * @param scene The scene the clip plane information are extracted from
  40292. * @param effect The effect we are binding the data to
  40293. */
  40294. MaterialHelper.BindClipPlane = function (effect, scene) {
  40295. if (scene.clipPlane) {
  40296. var clipPlane = scene.clipPlane;
  40297. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  40298. }
  40299. };
  40300. return MaterialHelper;
  40301. }());
  40302. BABYLON.MaterialHelper = MaterialHelper;
  40303. })(BABYLON || (BABYLON = {}));
  40304. //# sourceMappingURL=babylon.materialHelper.js.map
  40305. "use strict";
  40306. var BABYLON;
  40307. (function (BABYLON) {
  40308. var PushMaterial = /** @class */ (function (_super) {
  40309. __extends(PushMaterial, _super);
  40310. function PushMaterial(name, scene) {
  40311. var _this = _super.call(this, name, scene) || this;
  40312. _this._normalMatrix = new BABYLON.Matrix();
  40313. _this.storeEffectOnSubMeshes = true;
  40314. return _this;
  40315. }
  40316. PushMaterial.prototype.getEffect = function () {
  40317. return this._activeEffect;
  40318. };
  40319. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  40320. if (!mesh) {
  40321. return false;
  40322. }
  40323. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  40324. return true;
  40325. }
  40326. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  40327. };
  40328. /**
  40329. * Binds the given world matrix to the active effect
  40330. *
  40331. * @param world the matrix to bind
  40332. */
  40333. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40334. this._activeEffect.setMatrix("world", world);
  40335. };
  40336. /**
  40337. * Binds the given normal matrix to the active effect
  40338. *
  40339. * @param normalMatrix the matrix to bind
  40340. */
  40341. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  40342. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  40343. };
  40344. PushMaterial.prototype.bind = function (world, mesh) {
  40345. if (!mesh) {
  40346. return;
  40347. }
  40348. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  40349. };
  40350. PushMaterial.prototype._afterBind = function (mesh, effect) {
  40351. if (effect === void 0) { effect = null; }
  40352. _super.prototype._afterBind.call(this, mesh);
  40353. this.getScene()._cachedEffect = effect;
  40354. };
  40355. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  40356. if (visibility === void 0) { visibility = 1; }
  40357. return scene.isCachedMaterialInvalid(this, effect, visibility);
  40358. };
  40359. return PushMaterial;
  40360. }(BABYLON.Material));
  40361. BABYLON.PushMaterial = PushMaterial;
  40362. })(BABYLON || (BABYLON = {}));
  40363. //# sourceMappingURL=babylon.pushMaterial.js.map
  40364. "use strict";
  40365. var BABYLON;
  40366. (function (BABYLON) {
  40367. /** @ignore */
  40368. var StandardMaterialDefines = /** @class */ (function (_super) {
  40369. __extends(StandardMaterialDefines, _super);
  40370. function StandardMaterialDefines() {
  40371. var _this = _super.call(this) || this;
  40372. _this.MAINUV1 = false;
  40373. _this.MAINUV2 = false;
  40374. _this.DIFFUSE = false;
  40375. _this.DIFFUSEDIRECTUV = 0;
  40376. _this.AMBIENT = false;
  40377. _this.AMBIENTDIRECTUV = 0;
  40378. _this.OPACITY = false;
  40379. _this.OPACITYDIRECTUV = 0;
  40380. _this.OPACITYRGB = false;
  40381. _this.REFLECTION = false;
  40382. _this.EMISSIVE = false;
  40383. _this.EMISSIVEDIRECTUV = 0;
  40384. _this.SPECULAR = false;
  40385. _this.SPECULARDIRECTUV = 0;
  40386. _this.BUMP = false;
  40387. _this.BUMPDIRECTUV = 0;
  40388. _this.PARALLAX = false;
  40389. _this.PARALLAXOCCLUSION = false;
  40390. _this.SPECULAROVERALPHA = false;
  40391. _this.CLIPPLANE = false;
  40392. _this.ALPHATEST = false;
  40393. _this.DEPTHPREPASS = false;
  40394. _this.ALPHAFROMDIFFUSE = false;
  40395. _this.POINTSIZE = false;
  40396. _this.FOG = false;
  40397. _this.SPECULARTERM = false;
  40398. _this.DIFFUSEFRESNEL = false;
  40399. _this.OPACITYFRESNEL = false;
  40400. _this.REFLECTIONFRESNEL = false;
  40401. _this.REFRACTIONFRESNEL = false;
  40402. _this.EMISSIVEFRESNEL = false;
  40403. _this.FRESNEL = false;
  40404. _this.NORMAL = false;
  40405. _this.UV1 = false;
  40406. _this.UV2 = false;
  40407. _this.VERTEXCOLOR = false;
  40408. _this.VERTEXALPHA = false;
  40409. _this.NUM_BONE_INFLUENCERS = 0;
  40410. _this.BonesPerMesh = 0;
  40411. _this.INSTANCES = false;
  40412. _this.GLOSSINESS = false;
  40413. _this.ROUGHNESS = false;
  40414. _this.EMISSIVEASILLUMINATION = false;
  40415. _this.LINKEMISSIVEWITHDIFFUSE = false;
  40416. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  40417. _this.LIGHTMAP = false;
  40418. _this.LIGHTMAPDIRECTUV = 0;
  40419. _this.OBJECTSPACE_NORMALMAP = false;
  40420. _this.USELIGHTMAPASSHADOWMAP = false;
  40421. _this.REFLECTIONMAP_3D = false;
  40422. _this.REFLECTIONMAP_SPHERICAL = false;
  40423. _this.REFLECTIONMAP_PLANAR = false;
  40424. _this.REFLECTIONMAP_CUBIC = false;
  40425. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40426. _this.REFLECTIONMAP_PROJECTION = false;
  40427. _this.REFLECTIONMAP_SKYBOX = false;
  40428. _this.REFLECTIONMAP_EXPLICIT = false;
  40429. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40430. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40431. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40432. _this.INVERTCUBICMAP = false;
  40433. _this.LOGARITHMICDEPTH = false;
  40434. _this.REFRACTION = false;
  40435. _this.REFRACTIONMAP_3D = false;
  40436. _this.REFLECTIONOVERALPHA = false;
  40437. _this.TWOSIDEDLIGHTING = false;
  40438. _this.SHADOWFLOAT = false;
  40439. _this.MORPHTARGETS = false;
  40440. _this.MORPHTARGETS_NORMAL = false;
  40441. _this.MORPHTARGETS_TANGENT = false;
  40442. _this.NUM_MORPH_INFLUENCERS = 0;
  40443. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  40444. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  40445. _this.IMAGEPROCESSING = false;
  40446. _this.VIGNETTE = false;
  40447. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40448. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40449. _this.TONEMAPPING = false;
  40450. _this.CONTRAST = false;
  40451. _this.COLORCURVES = false;
  40452. _this.COLORGRADING = false;
  40453. _this.COLORGRADING3D = false;
  40454. _this.SAMPLER3DGREENDEPTH = false;
  40455. _this.SAMPLER3DBGRMAP = false;
  40456. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40457. _this.EXPOSURE = false;
  40458. _this.rebuild();
  40459. return _this;
  40460. }
  40461. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  40462. var modes = [
  40463. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  40464. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  40465. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  40466. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  40467. ];
  40468. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  40469. var mode = modes_1[_i];
  40470. this[mode] = (mode === modeToEnable);
  40471. }
  40472. };
  40473. return StandardMaterialDefines;
  40474. }(BABYLON.MaterialDefines));
  40475. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  40476. var StandardMaterial = /** @class */ (function (_super) {
  40477. __extends(StandardMaterial, _super);
  40478. function StandardMaterial(name, scene) {
  40479. var _this = _super.call(this, name, scene) || this;
  40480. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  40481. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  40482. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  40483. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40484. _this.specularPower = 64;
  40485. _this._useAlphaFromDiffuseTexture = false;
  40486. _this._useEmissiveAsIllumination = false;
  40487. _this._linkEmissiveWithDiffuse = false;
  40488. _this._useSpecularOverAlpha = false;
  40489. _this._useReflectionOverAlpha = false;
  40490. _this._disableLighting = false;
  40491. _this._useObjectSpaceNormalMap = false;
  40492. _this._useParallax = false;
  40493. _this._useParallaxOcclusion = false;
  40494. _this.parallaxScaleBias = 0.05;
  40495. _this._roughness = 0;
  40496. _this.indexOfRefraction = 0.98;
  40497. _this.invertRefractionY = true;
  40498. _this._useLightmapAsShadowmap = false;
  40499. _this._useReflectionFresnelFromSpecular = false;
  40500. _this._useGlossinessFromSpecularMapAlpha = false;
  40501. _this._maxSimultaneousLights = 4;
  40502. /**
  40503. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40504. */
  40505. _this._invertNormalMapX = false;
  40506. /**
  40507. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40508. */
  40509. _this._invertNormalMapY = false;
  40510. /**
  40511. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40512. */
  40513. _this._twoSidedLighting = false;
  40514. _this._renderTargets = new BABYLON.SmartArray(16);
  40515. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  40516. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40517. // Setup the default processing configuration to the scene.
  40518. _this._attachImageProcessingConfiguration(null);
  40519. _this.getRenderTargetTextures = function () {
  40520. _this._renderTargets.reset();
  40521. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40522. _this._renderTargets.push(_this._reflectionTexture);
  40523. }
  40524. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40525. _this._renderTargets.push(_this._refractionTexture);
  40526. }
  40527. return _this._renderTargets;
  40528. };
  40529. return _this;
  40530. }
  40531. ;
  40532. ;
  40533. ;
  40534. ;
  40535. ;
  40536. ;
  40537. ;
  40538. ;
  40539. ;
  40540. ;
  40541. ;
  40542. ;
  40543. ;
  40544. ;
  40545. ;
  40546. ;
  40547. ;
  40548. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  40549. /**
  40550. * Gets the image processing configuration used either in this material.
  40551. */
  40552. get: function () {
  40553. return this._imageProcessingConfiguration;
  40554. },
  40555. /**
  40556. * Sets the Default image processing configuration used either in the this material.
  40557. *
  40558. * If sets to null, the scene one is in use.
  40559. */
  40560. set: function (value) {
  40561. this._attachImageProcessingConfiguration(value);
  40562. // Ensure the effect will be rebuilt.
  40563. this._markAllSubMeshesAsTexturesDirty();
  40564. },
  40565. enumerable: true,
  40566. configurable: true
  40567. });
  40568. /**
  40569. * Attaches a new image processing configuration to the Standard Material.
  40570. * @param configuration
  40571. */
  40572. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40573. var _this = this;
  40574. if (configuration === this._imageProcessingConfiguration) {
  40575. return;
  40576. }
  40577. // Detaches observer.
  40578. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40579. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40580. }
  40581. // Pick the scene configuration if needed.
  40582. if (!configuration) {
  40583. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40584. }
  40585. else {
  40586. this._imageProcessingConfiguration = configuration;
  40587. }
  40588. // Attaches observer.
  40589. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40590. _this._markAllSubMeshesAsImageProcessingDirty();
  40591. });
  40592. };
  40593. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  40594. /**
  40595. * Gets wether the color curves effect is enabled.
  40596. */
  40597. get: function () {
  40598. return this.imageProcessingConfiguration.colorCurvesEnabled;
  40599. },
  40600. /**
  40601. * Sets wether the color curves effect is enabled.
  40602. */
  40603. set: function (value) {
  40604. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  40605. },
  40606. enumerable: true,
  40607. configurable: true
  40608. });
  40609. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  40610. /**
  40611. * Gets wether the color grading effect is enabled.
  40612. */
  40613. get: function () {
  40614. return this.imageProcessingConfiguration.colorGradingEnabled;
  40615. },
  40616. /**
  40617. * Gets wether the color grading effect is enabled.
  40618. */
  40619. set: function (value) {
  40620. this.imageProcessingConfiguration.colorGradingEnabled = value;
  40621. },
  40622. enumerable: true,
  40623. configurable: true
  40624. });
  40625. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  40626. /**
  40627. * Gets wether tonemapping is enabled or not.
  40628. */
  40629. get: function () {
  40630. return this._imageProcessingConfiguration.toneMappingEnabled;
  40631. },
  40632. /**
  40633. * Sets wether tonemapping is enabled or not
  40634. */
  40635. set: function (value) {
  40636. this._imageProcessingConfiguration.toneMappingEnabled = value;
  40637. },
  40638. enumerable: true,
  40639. configurable: true
  40640. });
  40641. ;
  40642. ;
  40643. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  40644. /**
  40645. * The camera exposure used on this material.
  40646. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40647. * This corresponds to a photographic exposure.
  40648. */
  40649. get: function () {
  40650. return this._imageProcessingConfiguration.exposure;
  40651. },
  40652. /**
  40653. * The camera exposure used on this material.
  40654. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40655. * This corresponds to a photographic exposure.
  40656. */
  40657. set: function (value) {
  40658. this._imageProcessingConfiguration.exposure = value;
  40659. },
  40660. enumerable: true,
  40661. configurable: true
  40662. });
  40663. ;
  40664. ;
  40665. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  40666. /**
  40667. * Gets The camera contrast used on this material.
  40668. */
  40669. get: function () {
  40670. return this._imageProcessingConfiguration.contrast;
  40671. },
  40672. /**
  40673. * Sets The camera contrast used on this material.
  40674. */
  40675. set: function (value) {
  40676. this._imageProcessingConfiguration.contrast = value;
  40677. },
  40678. enumerable: true,
  40679. configurable: true
  40680. });
  40681. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  40682. /**
  40683. * Gets the Color Grading 2D Lookup Texture.
  40684. */
  40685. get: function () {
  40686. return this._imageProcessingConfiguration.colorGradingTexture;
  40687. },
  40688. /**
  40689. * Sets the Color Grading 2D Lookup Texture.
  40690. */
  40691. set: function (value) {
  40692. this._imageProcessingConfiguration.colorGradingTexture = value;
  40693. },
  40694. enumerable: true,
  40695. configurable: true
  40696. });
  40697. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  40698. /**
  40699. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40700. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40701. * 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;
  40702. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40703. */
  40704. get: function () {
  40705. return this._imageProcessingConfiguration.colorCurves;
  40706. },
  40707. /**
  40708. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40709. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40710. * 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;
  40711. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40712. */
  40713. set: function (value) {
  40714. this._imageProcessingConfiguration.colorCurves = value;
  40715. },
  40716. enumerable: true,
  40717. configurable: true
  40718. });
  40719. StandardMaterial.prototype.getClassName = function () {
  40720. return "StandardMaterial";
  40721. };
  40722. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  40723. get: function () {
  40724. return this._useLogarithmicDepth;
  40725. },
  40726. set: function (value) {
  40727. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40728. this._markAllSubMeshesAsMiscDirty();
  40729. },
  40730. enumerable: true,
  40731. configurable: true
  40732. });
  40733. StandardMaterial.prototype.needAlphaBlending = function () {
  40734. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  40735. };
  40736. StandardMaterial.prototype.needAlphaTesting = function () {
  40737. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  40738. };
  40739. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  40740. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  40741. };
  40742. StandardMaterial.prototype.getAlphaTestTexture = function () {
  40743. return this._diffuseTexture;
  40744. };
  40745. /**
  40746. * Child classes can use it to update shaders
  40747. */
  40748. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40749. if (useInstances === void 0) { useInstances = false; }
  40750. if (subMesh.effect && this.isFrozen) {
  40751. if (this._wasPreviouslyReady && subMesh.effect) {
  40752. return true;
  40753. }
  40754. }
  40755. if (!subMesh._materialDefines) {
  40756. subMesh._materialDefines = new StandardMaterialDefines();
  40757. }
  40758. var scene = this.getScene();
  40759. var defines = subMesh._materialDefines;
  40760. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40761. if (defines._renderId === scene.getRenderId()) {
  40762. return true;
  40763. }
  40764. }
  40765. var engine = scene.getEngine();
  40766. // Lights
  40767. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40768. // Textures
  40769. if (defines._areTexturesDirty) {
  40770. defines._needUVs = false;
  40771. defines.MAINUV1 = false;
  40772. defines.MAINUV2 = false;
  40773. if (scene.texturesEnabled) {
  40774. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40775. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  40776. return false;
  40777. }
  40778. else {
  40779. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  40780. }
  40781. }
  40782. else {
  40783. defines.DIFFUSE = false;
  40784. }
  40785. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40786. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40787. return false;
  40788. }
  40789. else {
  40790. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40791. }
  40792. }
  40793. else {
  40794. defines.AMBIENT = false;
  40795. }
  40796. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40797. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40798. return false;
  40799. }
  40800. else {
  40801. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40802. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40803. }
  40804. }
  40805. else {
  40806. defines.OPACITY = false;
  40807. }
  40808. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40809. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  40810. return false;
  40811. }
  40812. else {
  40813. defines._needNormals = true;
  40814. defines.REFLECTION = true;
  40815. defines.ROUGHNESS = (this._roughness > 0);
  40816. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  40817. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  40818. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  40819. switch (this._reflectionTexture.coordinatesMode) {
  40820. case BABYLON.Texture.CUBIC_MODE:
  40821. case BABYLON.Texture.INVCUBIC_MODE:
  40822. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  40823. break;
  40824. case BABYLON.Texture.EXPLICIT_MODE:
  40825. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  40826. break;
  40827. case BABYLON.Texture.PLANAR_MODE:
  40828. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  40829. break;
  40830. case BABYLON.Texture.PROJECTION_MODE:
  40831. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  40832. break;
  40833. case BABYLON.Texture.SKYBOX_MODE:
  40834. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  40835. break;
  40836. case BABYLON.Texture.SPHERICAL_MODE:
  40837. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  40838. break;
  40839. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40840. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  40841. break;
  40842. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40843. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  40844. break;
  40845. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40846. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  40847. break;
  40848. }
  40849. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  40850. }
  40851. }
  40852. else {
  40853. defines.REFLECTION = false;
  40854. }
  40855. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40856. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40857. return false;
  40858. }
  40859. else {
  40860. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40861. }
  40862. }
  40863. else {
  40864. defines.EMISSIVE = false;
  40865. }
  40866. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40867. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40868. return false;
  40869. }
  40870. else {
  40871. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40872. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40873. }
  40874. }
  40875. else {
  40876. defines.LIGHTMAP = false;
  40877. }
  40878. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40879. if (!this._specularTexture.isReadyOrNotBlocking()) {
  40880. return false;
  40881. }
  40882. else {
  40883. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  40884. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  40885. }
  40886. }
  40887. else {
  40888. defines.SPECULAR = false;
  40889. }
  40890. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  40891. // Bump texure can not be not blocking.
  40892. if (!this._bumpTexture.isReady()) {
  40893. return false;
  40894. }
  40895. else {
  40896. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40897. defines.PARALLAX = this._useParallax;
  40898. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  40899. }
  40900. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40901. }
  40902. else {
  40903. defines.BUMP = false;
  40904. }
  40905. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40906. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  40907. return false;
  40908. }
  40909. else {
  40910. defines._needUVs = true;
  40911. defines.REFRACTION = true;
  40912. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  40913. }
  40914. }
  40915. else {
  40916. defines.REFRACTION = false;
  40917. }
  40918. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40919. }
  40920. else {
  40921. defines.DIFFUSE = false;
  40922. defines.AMBIENT = false;
  40923. defines.OPACITY = false;
  40924. defines.REFLECTION = false;
  40925. defines.EMISSIVE = false;
  40926. defines.LIGHTMAP = false;
  40927. defines.BUMP = false;
  40928. defines.REFRACTION = false;
  40929. }
  40930. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40931. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40932. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40933. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40934. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40935. }
  40936. if (defines._areImageProcessingDirty) {
  40937. if (!this._imageProcessingConfiguration.isReady()) {
  40938. return false;
  40939. }
  40940. this._imageProcessingConfiguration.prepareDefines(defines);
  40941. }
  40942. if (defines._areFresnelDirty) {
  40943. if (StandardMaterial.FresnelEnabled) {
  40944. // Fresnel
  40945. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40946. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40947. this._reflectionFresnelParameters) {
  40948. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40949. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40950. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40951. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40952. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40953. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40954. defines._needNormals = true;
  40955. defines.FRESNEL = true;
  40956. }
  40957. }
  40958. else {
  40959. defines.FRESNEL = false;
  40960. }
  40961. }
  40962. // Misc.
  40963. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40964. // Attribs
  40965. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40966. // Values that need to be evaluated on every frame
  40967. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40968. // Get correct effect
  40969. if (defines.isDirty) {
  40970. defines.markAsProcessed();
  40971. scene.resetCachedMaterial();
  40972. // Fallbacks
  40973. var fallbacks = new BABYLON.EffectFallbacks();
  40974. if (defines.REFLECTION) {
  40975. fallbacks.addFallback(0, "REFLECTION");
  40976. }
  40977. if (defines.SPECULAR) {
  40978. fallbacks.addFallback(0, "SPECULAR");
  40979. }
  40980. if (defines.BUMP) {
  40981. fallbacks.addFallback(0, "BUMP");
  40982. }
  40983. if (defines.PARALLAX) {
  40984. fallbacks.addFallback(1, "PARALLAX");
  40985. }
  40986. if (defines.PARALLAXOCCLUSION) {
  40987. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40988. }
  40989. if (defines.SPECULAROVERALPHA) {
  40990. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40991. }
  40992. if (defines.FOG) {
  40993. fallbacks.addFallback(1, "FOG");
  40994. }
  40995. if (defines.POINTSIZE) {
  40996. fallbacks.addFallback(0, "POINTSIZE");
  40997. }
  40998. if (defines.LOGARITHMICDEPTH) {
  40999. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41000. }
  41001. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41002. if (defines.SPECULARTERM) {
  41003. fallbacks.addFallback(0, "SPECULARTERM");
  41004. }
  41005. if (defines.DIFFUSEFRESNEL) {
  41006. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41007. }
  41008. if (defines.OPACITYFRESNEL) {
  41009. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41010. }
  41011. if (defines.REFLECTIONFRESNEL) {
  41012. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41013. }
  41014. if (defines.EMISSIVEFRESNEL) {
  41015. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41016. }
  41017. if (defines.FRESNEL) {
  41018. fallbacks.addFallback(4, "FRESNEL");
  41019. }
  41020. //Attributes
  41021. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41022. if (defines.NORMAL) {
  41023. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41024. }
  41025. if (defines.UV1) {
  41026. attribs.push(BABYLON.VertexBuffer.UVKind);
  41027. }
  41028. if (defines.UV2) {
  41029. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41030. }
  41031. if (defines.VERTEXCOLOR) {
  41032. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41033. }
  41034. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41035. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41036. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41037. var shaderName = "default";
  41038. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41039. "vFogInfos", "vFogColor", "pointSize",
  41040. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41041. "mBones",
  41042. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41043. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41044. "vReflectionPosition", "vReflectionSize",
  41045. "logarithmicDepthConstant", "vTangentSpaceParams"
  41046. ];
  41047. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41048. var uniformBuffers = ["Material", "Scene"];
  41049. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41050. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41051. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41052. uniformsNames: uniforms,
  41053. uniformBuffersNames: uniformBuffers,
  41054. samplers: samplers,
  41055. defines: defines,
  41056. maxSimultaneousLights: this._maxSimultaneousLights
  41057. });
  41058. if (this.customShaderNameResolve) {
  41059. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41060. }
  41061. var join = defines.toString();
  41062. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41063. attributes: attribs,
  41064. uniformsNames: uniforms,
  41065. uniformBuffersNames: uniformBuffers,
  41066. samplers: samplers,
  41067. defines: join,
  41068. fallbacks: fallbacks,
  41069. onCompiled: this.onCompiled,
  41070. onError: this.onError,
  41071. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41072. }, engine), defines);
  41073. this.buildUniformLayout();
  41074. }
  41075. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41076. return false;
  41077. }
  41078. defines._renderId = scene.getRenderId();
  41079. this._wasPreviouslyReady = true;
  41080. return true;
  41081. };
  41082. StandardMaterial.prototype.buildUniformLayout = function () {
  41083. // Order is important !
  41084. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41085. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41086. this._uniformBuffer.addUniform("opacityParts", 4);
  41087. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41088. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41089. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41090. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41091. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41092. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41093. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41094. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41095. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41096. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41097. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41098. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41099. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41100. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41101. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41102. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41103. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41104. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41105. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41106. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41107. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41108. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41109. this._uniformBuffer.addUniform("specularMatrix", 16);
  41110. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41111. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41112. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41113. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41114. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41115. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41116. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41117. this._uniformBuffer.addUniform("pointSize", 1);
  41118. this._uniformBuffer.create();
  41119. };
  41120. StandardMaterial.prototype.unbind = function () {
  41121. if (this._activeEffect) {
  41122. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41123. this._activeEffect.setTexture("reflection2DSampler", null);
  41124. }
  41125. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41126. this._activeEffect.setTexture("refraction2DSampler", null);
  41127. }
  41128. }
  41129. _super.prototype.unbind.call(this);
  41130. };
  41131. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41132. var scene = this.getScene();
  41133. var defines = subMesh._materialDefines;
  41134. if (!defines) {
  41135. return;
  41136. }
  41137. var effect = subMesh.effect;
  41138. if (!effect) {
  41139. return;
  41140. }
  41141. this._activeEffect = effect;
  41142. // Matrices
  41143. this.bindOnlyWorldMatrix(world);
  41144. // Normal Matrix
  41145. if (defines.OBJECTSPACE_NORMALMAP) {
  41146. world.toNormalMatrix(this._normalMatrix);
  41147. this.bindOnlyNormalMatrix(this._normalMatrix);
  41148. }
  41149. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41150. // Bones
  41151. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41152. if (mustRebind) {
  41153. this._uniformBuffer.bindToEffect(effect, "Material");
  41154. this.bindViewProjection(effect);
  41155. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41156. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41157. // Fresnel
  41158. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41159. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41160. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41161. }
  41162. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  41163. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  41164. }
  41165. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  41166. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  41167. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  41168. }
  41169. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  41170. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  41171. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  41172. }
  41173. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  41174. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  41175. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  41176. }
  41177. }
  41178. // Textures
  41179. if (scene.texturesEnabled) {
  41180. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41181. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  41182. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  41183. }
  41184. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41185. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  41186. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41187. }
  41188. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41189. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41190. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41191. }
  41192. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41193. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  41194. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  41195. if (this._reflectionTexture.boundingBoxSize) {
  41196. var cubeTexture = this._reflectionTexture;
  41197. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41198. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41199. }
  41200. }
  41201. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41202. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41203. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41204. }
  41205. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41206. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41207. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41208. }
  41209. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41210. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  41211. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  41212. }
  41213. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41214. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  41215. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41216. if (scene._mirroredCameraPosition) {
  41217. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41218. }
  41219. else {
  41220. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41221. }
  41222. }
  41223. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41224. var depth = 1.0;
  41225. if (!this._refractionTexture.isCube) {
  41226. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  41227. if (this._refractionTexture.depth) {
  41228. depth = this._refractionTexture.depth;
  41229. }
  41230. }
  41231. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  41232. }
  41233. }
  41234. // Point size
  41235. if (this.pointsCloud) {
  41236. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41237. }
  41238. if (defines.SPECULARTERM) {
  41239. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  41240. }
  41241. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  41242. // Diffuse
  41243. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  41244. }
  41245. // Textures
  41246. if (scene.texturesEnabled) {
  41247. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41248. effect.setTexture("diffuseSampler", this._diffuseTexture);
  41249. }
  41250. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41251. effect.setTexture("ambientSampler", this._ambientTexture);
  41252. }
  41253. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41254. effect.setTexture("opacitySampler", this._opacityTexture);
  41255. }
  41256. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41257. if (this._reflectionTexture.isCube) {
  41258. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  41259. }
  41260. else {
  41261. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  41262. }
  41263. }
  41264. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41265. effect.setTexture("emissiveSampler", this._emissiveTexture);
  41266. }
  41267. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41268. effect.setTexture("lightmapSampler", this._lightmapTexture);
  41269. }
  41270. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41271. effect.setTexture("specularSampler", this._specularTexture);
  41272. }
  41273. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41274. effect.setTexture("bumpSampler", this._bumpTexture);
  41275. }
  41276. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41277. var depth = 1.0;
  41278. if (this._refractionTexture.isCube) {
  41279. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  41280. }
  41281. else {
  41282. effect.setTexture("refraction2DSampler", this._refractionTexture);
  41283. }
  41284. }
  41285. }
  41286. // Clip plane
  41287. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  41288. // Colors
  41289. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  41290. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  41291. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41292. }
  41293. if (mustRebind || !this.isFrozen) {
  41294. // Lights
  41295. if (scene.lightsEnabled && !this._disableLighting) {
  41296. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  41297. }
  41298. // View
  41299. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  41300. this.bindView(effect);
  41301. }
  41302. // Fog
  41303. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  41304. // Morph targets
  41305. if (defines.NUM_MORPH_INFLUENCERS) {
  41306. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  41307. }
  41308. // Log. depth
  41309. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  41310. // image processing
  41311. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  41312. this._imageProcessingConfiguration.bind(this._activeEffect);
  41313. }
  41314. }
  41315. this._uniformBuffer.update();
  41316. this._afterBind(mesh, this._activeEffect);
  41317. };
  41318. StandardMaterial.prototype.getAnimatables = function () {
  41319. var results = [];
  41320. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  41321. results.push(this._diffuseTexture);
  41322. }
  41323. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41324. results.push(this._ambientTexture);
  41325. }
  41326. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41327. results.push(this._opacityTexture);
  41328. }
  41329. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41330. results.push(this._reflectionTexture);
  41331. }
  41332. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41333. results.push(this._emissiveTexture);
  41334. }
  41335. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  41336. results.push(this._specularTexture);
  41337. }
  41338. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41339. results.push(this._bumpTexture);
  41340. }
  41341. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41342. results.push(this._lightmapTexture);
  41343. }
  41344. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41345. results.push(this._refractionTexture);
  41346. }
  41347. return results;
  41348. };
  41349. StandardMaterial.prototype.getActiveTextures = function () {
  41350. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41351. if (this._diffuseTexture) {
  41352. activeTextures.push(this._diffuseTexture);
  41353. }
  41354. if (this._ambientTexture) {
  41355. activeTextures.push(this._ambientTexture);
  41356. }
  41357. if (this._opacityTexture) {
  41358. activeTextures.push(this._opacityTexture);
  41359. }
  41360. if (this._reflectionTexture) {
  41361. activeTextures.push(this._reflectionTexture);
  41362. }
  41363. if (this._emissiveTexture) {
  41364. activeTextures.push(this._emissiveTexture);
  41365. }
  41366. if (this._specularTexture) {
  41367. activeTextures.push(this._specularTexture);
  41368. }
  41369. if (this._bumpTexture) {
  41370. activeTextures.push(this._bumpTexture);
  41371. }
  41372. if (this._lightmapTexture) {
  41373. activeTextures.push(this._lightmapTexture);
  41374. }
  41375. if (this._refractionTexture) {
  41376. activeTextures.push(this._refractionTexture);
  41377. }
  41378. return activeTextures;
  41379. };
  41380. StandardMaterial.prototype.hasTexture = function (texture) {
  41381. if (_super.prototype.hasTexture.call(this, texture)) {
  41382. return true;
  41383. }
  41384. if (this._diffuseTexture === texture) {
  41385. return true;
  41386. }
  41387. if (this._ambientTexture === texture) {
  41388. return true;
  41389. }
  41390. if (this._opacityTexture === texture) {
  41391. return true;
  41392. }
  41393. if (this._reflectionTexture === texture) {
  41394. return true;
  41395. }
  41396. if (this._emissiveTexture === texture) {
  41397. return true;
  41398. }
  41399. if (this._specularTexture === texture) {
  41400. return true;
  41401. }
  41402. if (this._bumpTexture === texture) {
  41403. return true;
  41404. }
  41405. if (this._lightmapTexture === texture) {
  41406. return true;
  41407. }
  41408. if (this._refractionTexture === texture) {
  41409. return true;
  41410. }
  41411. return false;
  41412. };
  41413. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41414. if (forceDisposeTextures) {
  41415. if (this._diffuseTexture) {
  41416. this._diffuseTexture.dispose();
  41417. }
  41418. if (this._ambientTexture) {
  41419. this._ambientTexture.dispose();
  41420. }
  41421. if (this._opacityTexture) {
  41422. this._opacityTexture.dispose();
  41423. }
  41424. if (this._reflectionTexture) {
  41425. this._reflectionTexture.dispose();
  41426. }
  41427. if (this._emissiveTexture) {
  41428. this._emissiveTexture.dispose();
  41429. }
  41430. if (this._specularTexture) {
  41431. this._specularTexture.dispose();
  41432. }
  41433. if (this._bumpTexture) {
  41434. this._bumpTexture.dispose();
  41435. }
  41436. if (this._lightmapTexture) {
  41437. this._lightmapTexture.dispose();
  41438. }
  41439. if (this._refractionTexture) {
  41440. this._refractionTexture.dispose();
  41441. }
  41442. }
  41443. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41444. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41445. }
  41446. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41447. };
  41448. StandardMaterial.prototype.clone = function (name) {
  41449. var _this = this;
  41450. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  41451. result.name = name;
  41452. result.id = name;
  41453. return result;
  41454. };
  41455. StandardMaterial.prototype.serialize = function () {
  41456. return BABYLON.SerializationHelper.Serialize(this);
  41457. };
  41458. // Statics
  41459. StandardMaterial.Parse = function (source, scene, rootUrl) {
  41460. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  41461. };
  41462. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  41463. get: function () {
  41464. return StandardMaterial._DiffuseTextureEnabled;
  41465. },
  41466. set: function (value) {
  41467. if (StandardMaterial._DiffuseTextureEnabled === value) {
  41468. return;
  41469. }
  41470. StandardMaterial._DiffuseTextureEnabled = value;
  41471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41472. },
  41473. enumerable: true,
  41474. configurable: true
  41475. });
  41476. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  41477. get: function () {
  41478. return StandardMaterial._AmbientTextureEnabled;
  41479. },
  41480. set: function (value) {
  41481. if (StandardMaterial._AmbientTextureEnabled === value) {
  41482. return;
  41483. }
  41484. StandardMaterial._AmbientTextureEnabled = value;
  41485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41486. },
  41487. enumerable: true,
  41488. configurable: true
  41489. });
  41490. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  41491. get: function () {
  41492. return StandardMaterial._OpacityTextureEnabled;
  41493. },
  41494. set: function (value) {
  41495. if (StandardMaterial._OpacityTextureEnabled === value) {
  41496. return;
  41497. }
  41498. StandardMaterial._OpacityTextureEnabled = value;
  41499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41500. },
  41501. enumerable: true,
  41502. configurable: true
  41503. });
  41504. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  41505. get: function () {
  41506. return StandardMaterial._ReflectionTextureEnabled;
  41507. },
  41508. set: function (value) {
  41509. if (StandardMaterial._ReflectionTextureEnabled === value) {
  41510. return;
  41511. }
  41512. StandardMaterial._ReflectionTextureEnabled = value;
  41513. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41514. },
  41515. enumerable: true,
  41516. configurable: true
  41517. });
  41518. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  41519. get: function () {
  41520. return StandardMaterial._EmissiveTextureEnabled;
  41521. },
  41522. set: function (value) {
  41523. if (StandardMaterial._EmissiveTextureEnabled === value) {
  41524. return;
  41525. }
  41526. StandardMaterial._EmissiveTextureEnabled = value;
  41527. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41528. },
  41529. enumerable: true,
  41530. configurable: true
  41531. });
  41532. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  41533. get: function () {
  41534. return StandardMaterial._SpecularTextureEnabled;
  41535. },
  41536. set: function (value) {
  41537. if (StandardMaterial._SpecularTextureEnabled === value) {
  41538. return;
  41539. }
  41540. StandardMaterial._SpecularTextureEnabled = value;
  41541. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41542. },
  41543. enumerable: true,
  41544. configurable: true
  41545. });
  41546. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  41547. get: function () {
  41548. return StandardMaterial._BumpTextureEnabled;
  41549. },
  41550. set: function (value) {
  41551. if (StandardMaterial._BumpTextureEnabled === value) {
  41552. return;
  41553. }
  41554. StandardMaterial._BumpTextureEnabled = value;
  41555. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41556. },
  41557. enumerable: true,
  41558. configurable: true
  41559. });
  41560. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  41561. get: function () {
  41562. return StandardMaterial._LightmapTextureEnabled;
  41563. },
  41564. set: function (value) {
  41565. if (StandardMaterial._LightmapTextureEnabled === value) {
  41566. return;
  41567. }
  41568. StandardMaterial._LightmapTextureEnabled = value;
  41569. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41570. },
  41571. enumerable: true,
  41572. configurable: true
  41573. });
  41574. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  41575. get: function () {
  41576. return StandardMaterial._RefractionTextureEnabled;
  41577. },
  41578. set: function (value) {
  41579. if (StandardMaterial._RefractionTextureEnabled === value) {
  41580. return;
  41581. }
  41582. StandardMaterial._RefractionTextureEnabled = value;
  41583. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41584. },
  41585. enumerable: true,
  41586. configurable: true
  41587. });
  41588. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  41589. get: function () {
  41590. return StandardMaterial._ColorGradingTextureEnabled;
  41591. },
  41592. set: function (value) {
  41593. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  41594. return;
  41595. }
  41596. StandardMaterial._ColorGradingTextureEnabled = value;
  41597. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41598. },
  41599. enumerable: true,
  41600. configurable: true
  41601. });
  41602. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  41603. get: function () {
  41604. return StandardMaterial._FresnelEnabled;
  41605. },
  41606. set: function (value) {
  41607. if (StandardMaterial._FresnelEnabled === value) {
  41608. return;
  41609. }
  41610. StandardMaterial._FresnelEnabled = value;
  41611. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  41612. },
  41613. enumerable: true,
  41614. configurable: true
  41615. });
  41616. // Flags used to enable or disable a type of texture for all Standard Materials
  41617. StandardMaterial._DiffuseTextureEnabled = true;
  41618. StandardMaterial._AmbientTextureEnabled = true;
  41619. StandardMaterial._OpacityTextureEnabled = true;
  41620. StandardMaterial._ReflectionTextureEnabled = true;
  41621. StandardMaterial._EmissiveTextureEnabled = true;
  41622. StandardMaterial._SpecularTextureEnabled = true;
  41623. StandardMaterial._BumpTextureEnabled = true;
  41624. StandardMaterial._LightmapTextureEnabled = true;
  41625. StandardMaterial._RefractionTextureEnabled = true;
  41626. StandardMaterial._ColorGradingTextureEnabled = true;
  41627. StandardMaterial._FresnelEnabled = true;
  41628. __decorate([
  41629. BABYLON.serializeAsTexture("diffuseTexture")
  41630. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  41631. __decorate([
  41632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41633. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  41634. __decorate([
  41635. BABYLON.serializeAsTexture("ambientTexture")
  41636. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  41637. __decorate([
  41638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41639. ], StandardMaterial.prototype, "ambientTexture", void 0);
  41640. __decorate([
  41641. BABYLON.serializeAsTexture("opacityTexture")
  41642. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  41643. __decorate([
  41644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41645. ], StandardMaterial.prototype, "opacityTexture", void 0);
  41646. __decorate([
  41647. BABYLON.serializeAsTexture("reflectionTexture")
  41648. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  41649. __decorate([
  41650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41651. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  41652. __decorate([
  41653. BABYLON.serializeAsTexture("emissiveTexture")
  41654. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  41655. __decorate([
  41656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41657. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  41658. __decorate([
  41659. BABYLON.serializeAsTexture("specularTexture")
  41660. ], StandardMaterial.prototype, "_specularTexture", void 0);
  41661. __decorate([
  41662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41663. ], StandardMaterial.prototype, "specularTexture", void 0);
  41664. __decorate([
  41665. BABYLON.serializeAsTexture("bumpTexture")
  41666. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  41667. __decorate([
  41668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41669. ], StandardMaterial.prototype, "bumpTexture", void 0);
  41670. __decorate([
  41671. BABYLON.serializeAsTexture("lightmapTexture")
  41672. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  41673. __decorate([
  41674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41675. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  41676. __decorate([
  41677. BABYLON.serializeAsTexture("refractionTexture")
  41678. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  41679. __decorate([
  41680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41681. ], StandardMaterial.prototype, "refractionTexture", void 0);
  41682. __decorate([
  41683. BABYLON.serializeAsColor3("ambient")
  41684. ], StandardMaterial.prototype, "ambientColor", void 0);
  41685. __decorate([
  41686. BABYLON.serializeAsColor3("diffuse")
  41687. ], StandardMaterial.prototype, "diffuseColor", void 0);
  41688. __decorate([
  41689. BABYLON.serializeAsColor3("specular")
  41690. ], StandardMaterial.prototype, "specularColor", void 0);
  41691. __decorate([
  41692. BABYLON.serializeAsColor3("emissive")
  41693. ], StandardMaterial.prototype, "emissiveColor", void 0);
  41694. __decorate([
  41695. BABYLON.serialize()
  41696. ], StandardMaterial.prototype, "specularPower", void 0);
  41697. __decorate([
  41698. BABYLON.serialize("useAlphaFromDiffuseTexture")
  41699. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  41700. __decorate([
  41701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41702. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  41703. __decorate([
  41704. BABYLON.serialize("useEmissiveAsIllumination")
  41705. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  41706. __decorate([
  41707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41708. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  41709. __decorate([
  41710. BABYLON.serialize("linkEmissiveWithDiffuse")
  41711. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  41712. __decorate([
  41713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41714. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  41715. __decorate([
  41716. BABYLON.serialize("useSpecularOverAlpha")
  41717. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  41718. __decorate([
  41719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41720. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  41721. __decorate([
  41722. BABYLON.serialize("useReflectionOverAlpha")
  41723. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  41724. __decorate([
  41725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41726. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  41727. __decorate([
  41728. BABYLON.serialize("disableLighting")
  41729. ], StandardMaterial.prototype, "_disableLighting", void 0);
  41730. __decorate([
  41731. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41732. ], StandardMaterial.prototype, "disableLighting", void 0);
  41733. __decorate([
  41734. BABYLON.serialize("useObjectSpaceNormalMap")
  41735. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  41736. __decorate([
  41737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41738. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  41739. __decorate([
  41740. BABYLON.serialize("useParallax")
  41741. ], StandardMaterial.prototype, "_useParallax", void 0);
  41742. __decorate([
  41743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41744. ], StandardMaterial.prototype, "useParallax", void 0);
  41745. __decorate([
  41746. BABYLON.serialize("useParallaxOcclusion")
  41747. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  41748. __decorate([
  41749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41750. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  41751. __decorate([
  41752. BABYLON.serialize()
  41753. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  41754. __decorate([
  41755. BABYLON.serialize("roughness")
  41756. ], StandardMaterial.prototype, "_roughness", void 0);
  41757. __decorate([
  41758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41759. ], StandardMaterial.prototype, "roughness", void 0);
  41760. __decorate([
  41761. BABYLON.serialize()
  41762. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  41763. __decorate([
  41764. BABYLON.serialize()
  41765. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  41766. __decorate([
  41767. BABYLON.serialize("useLightmapAsShadowmap")
  41768. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  41769. __decorate([
  41770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41771. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41772. __decorate([
  41773. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  41774. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  41775. __decorate([
  41776. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41777. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  41778. __decorate([
  41779. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  41780. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  41781. __decorate([
  41782. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  41783. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  41784. __decorate([
  41785. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  41786. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  41787. __decorate([
  41788. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41789. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  41790. __decorate([
  41791. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  41792. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  41793. __decorate([
  41794. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41795. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  41796. __decorate([
  41797. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  41798. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  41799. __decorate([
  41800. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41801. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  41802. __decorate([
  41803. BABYLON.serialize("useReflectionFresnelFromSpecular")
  41804. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  41805. __decorate([
  41806. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41807. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  41808. __decorate([
  41809. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  41810. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  41811. __decorate([
  41812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41813. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  41814. __decorate([
  41815. BABYLON.serialize("maxSimultaneousLights")
  41816. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  41817. __decorate([
  41818. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41819. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  41820. __decorate([
  41821. BABYLON.serialize("invertNormalMapX")
  41822. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  41823. __decorate([
  41824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41825. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  41826. __decorate([
  41827. BABYLON.serialize("invertNormalMapY")
  41828. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  41829. __decorate([
  41830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41831. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  41832. __decorate([
  41833. BABYLON.serialize("twoSidedLighting")
  41834. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  41835. __decorate([
  41836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41837. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  41838. __decorate([
  41839. BABYLON.serialize()
  41840. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  41841. return StandardMaterial;
  41842. }(BABYLON.PushMaterial));
  41843. BABYLON.StandardMaterial = StandardMaterial;
  41844. })(BABYLON || (BABYLON = {}));
  41845. //# sourceMappingURL=babylon.standardMaterial.js.map
  41846. "use strict";
  41847. var BABYLON;
  41848. (function (BABYLON) {
  41849. /**
  41850. * Manages the defines for the PBR Material.
  41851. */
  41852. var PBRMaterialDefines = /** @class */ (function (_super) {
  41853. __extends(PBRMaterialDefines, _super);
  41854. /**
  41855. * Initializes the PBR Material defines.
  41856. */
  41857. function PBRMaterialDefines() {
  41858. var _this = _super.call(this) || this;
  41859. _this.PBR = true;
  41860. _this.MAINUV1 = false;
  41861. _this.MAINUV2 = false;
  41862. _this.UV1 = false;
  41863. _this.UV2 = false;
  41864. _this.ALBEDO = false;
  41865. _this.ALBEDODIRECTUV = 0;
  41866. _this.VERTEXCOLOR = false;
  41867. _this.AMBIENT = false;
  41868. _this.AMBIENTDIRECTUV = 0;
  41869. _this.AMBIENTINGRAYSCALE = false;
  41870. _this.OPACITY = false;
  41871. _this.VERTEXALPHA = false;
  41872. _this.OPACITYDIRECTUV = 0;
  41873. _this.OPACITYRGB = false;
  41874. _this.ALPHATEST = false;
  41875. _this.DEPTHPREPASS = false;
  41876. _this.ALPHABLEND = false;
  41877. _this.ALPHAFROMALBEDO = false;
  41878. _this.ALPHATESTVALUE = "0.5";
  41879. _this.SPECULAROVERALPHA = false;
  41880. _this.RADIANCEOVERALPHA = false;
  41881. _this.ALPHAFRESNEL = false;
  41882. _this.LINEARALPHAFRESNEL = false;
  41883. _this.PREMULTIPLYALPHA = false;
  41884. _this.EMISSIVE = false;
  41885. _this.EMISSIVEDIRECTUV = 0;
  41886. _this.REFLECTIVITY = false;
  41887. _this.REFLECTIVITYDIRECTUV = 0;
  41888. _this.SPECULARTERM = false;
  41889. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  41890. _this.MICROSURFACEAUTOMATIC = false;
  41891. _this.LODBASEDMICROSFURACE = false;
  41892. _this.MICROSURFACEMAP = false;
  41893. _this.MICROSURFACEMAPDIRECTUV = 0;
  41894. _this.METALLICWORKFLOW = false;
  41895. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  41896. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  41897. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  41898. _this.AOSTOREINMETALMAPRED = false;
  41899. _this.ENVIRONMENTBRDF = false;
  41900. _this.NORMAL = false;
  41901. _this.TANGENT = false;
  41902. _this.BUMP = false;
  41903. _this.BUMPDIRECTUV = 0;
  41904. _this.OBJECTSPACE_NORMALMAP = false;
  41905. _this.PARALLAX = false;
  41906. _this.PARALLAXOCCLUSION = false;
  41907. _this.NORMALXYSCALE = true;
  41908. _this.LIGHTMAP = false;
  41909. _this.LIGHTMAPDIRECTUV = 0;
  41910. _this.USELIGHTMAPASSHADOWMAP = false;
  41911. _this.GAMMALIGHTMAP = false;
  41912. _this.REFLECTION = false;
  41913. _this.REFLECTIONMAP_3D = false;
  41914. _this.REFLECTIONMAP_SPHERICAL = false;
  41915. _this.REFLECTIONMAP_PLANAR = false;
  41916. _this.REFLECTIONMAP_CUBIC = false;
  41917. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41918. _this.REFLECTIONMAP_PROJECTION = false;
  41919. _this.REFLECTIONMAP_SKYBOX = false;
  41920. _this.REFLECTIONMAP_EXPLICIT = false;
  41921. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41922. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41923. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41924. _this.INVERTCUBICMAP = false;
  41925. _this.USESPHERICALFROMREFLECTIONMAP = false;
  41926. _this.USESPHERICALINVERTEX = false;
  41927. _this.REFLECTIONMAP_OPPOSITEZ = false;
  41928. _this.LODINREFLECTIONALPHA = false;
  41929. _this.GAMMAREFLECTION = false;
  41930. _this.RADIANCEOCCLUSION = false;
  41931. _this.HORIZONOCCLUSION = false;
  41932. _this.REFRACTION = false;
  41933. _this.REFRACTIONMAP_3D = false;
  41934. _this.REFRACTIONMAP_OPPOSITEZ = false;
  41935. _this.LODINREFRACTIONALPHA = false;
  41936. _this.GAMMAREFRACTION = false;
  41937. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  41938. _this.INSTANCES = false;
  41939. _this.NUM_BONE_INFLUENCERS = 0;
  41940. _this.BonesPerMesh = 0;
  41941. _this.NONUNIFORMSCALING = false;
  41942. _this.MORPHTARGETS = false;
  41943. _this.MORPHTARGETS_NORMAL = false;
  41944. _this.MORPHTARGETS_TANGENT = false;
  41945. _this.NUM_MORPH_INFLUENCERS = 0;
  41946. _this.IMAGEPROCESSING = false;
  41947. _this.VIGNETTE = false;
  41948. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41949. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41950. _this.TONEMAPPING = false;
  41951. _this.CONTRAST = false;
  41952. _this.COLORCURVES = false;
  41953. _this.COLORGRADING = false;
  41954. _this.COLORGRADING3D = false;
  41955. _this.SAMPLER3DGREENDEPTH = false;
  41956. _this.SAMPLER3DBGRMAP = false;
  41957. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41958. _this.EXPOSURE = false;
  41959. _this.USEPHYSICALLIGHTFALLOFF = false;
  41960. _this.TWOSIDEDLIGHTING = false;
  41961. _this.SHADOWFLOAT = false;
  41962. _this.CLIPPLANE = false;
  41963. _this.POINTSIZE = false;
  41964. _this.FOG = false;
  41965. _this.LOGARITHMICDEPTH = false;
  41966. _this.FORCENORMALFORWARD = false;
  41967. _this.UNLIT = false;
  41968. _this.rebuild();
  41969. return _this;
  41970. }
  41971. /**
  41972. * Resets the PBR Material defines.
  41973. */
  41974. PBRMaterialDefines.prototype.reset = function () {
  41975. _super.prototype.reset.call(this);
  41976. this.ALPHATESTVALUE = "0.5";
  41977. this.PBR = true;
  41978. };
  41979. return PBRMaterialDefines;
  41980. }(BABYLON.MaterialDefines));
  41981. /**
  41982. * The Physically based material base class of BJS.
  41983. *
  41984. * This offers the main features of a standard PBR material.
  41985. * For more information, please refer to the documentation :
  41986. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41987. */
  41988. var PBRBaseMaterial = /** @class */ (function (_super) {
  41989. __extends(PBRBaseMaterial, _super);
  41990. /**
  41991. * Instantiates a new PBRMaterial instance.
  41992. *
  41993. * @param name The material name
  41994. * @param scene The scene the material will be use in.
  41995. */
  41996. function PBRBaseMaterial(name, scene) {
  41997. var _this = _super.call(this, name, scene) || this;
  41998. /**
  41999. * Intensity of the direct lights e.g. the four lights available in your scene.
  42000. * This impacts both the direct diffuse and specular highlights.
  42001. */
  42002. _this._directIntensity = 1.0;
  42003. /**
  42004. * Intensity of the emissive part of the material.
  42005. * This helps controlling the emissive effect without modifying the emissive color.
  42006. */
  42007. _this._emissiveIntensity = 1.0;
  42008. /**
  42009. * Intensity of the environment e.g. how much the environment will light the object
  42010. * either through harmonics for rough material or through the refelction for shiny ones.
  42011. */
  42012. _this._environmentIntensity = 1.0;
  42013. /**
  42014. * This is a special control allowing the reduction of the specular highlights coming from the
  42015. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42016. */
  42017. _this._specularIntensity = 1.0;
  42018. /**
  42019. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  42020. */
  42021. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  42022. /**
  42023. * Debug Control allowing disabling the bump map on this material.
  42024. */
  42025. _this._disableBumpMap = false;
  42026. /**
  42027. * AKA Occlusion Texture Intensity in other nomenclature.
  42028. */
  42029. _this._ambientTextureStrength = 1.0;
  42030. /**
  42031. * The color of a material in ambient lighting.
  42032. */
  42033. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  42034. /**
  42035. * AKA Diffuse Color in other nomenclature.
  42036. */
  42037. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  42038. /**
  42039. * AKA Specular Color in other nomenclature.
  42040. */
  42041. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42042. /**
  42043. * The color applied when light is reflected from a material.
  42044. */
  42045. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  42046. /**
  42047. * The color applied when light is emitted from a material.
  42048. */
  42049. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  42050. /**
  42051. * AKA Glossiness in other nomenclature.
  42052. */
  42053. _this._microSurface = 0.9;
  42054. /**
  42055. * source material index of refraction (IOR)' / 'destination material IOR.
  42056. */
  42057. _this._indexOfRefraction = 0.66;
  42058. /**
  42059. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42060. */
  42061. _this._invertRefractionY = false;
  42062. /**
  42063. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42064. * Materials half opaque for instance using refraction could benefit from this control.
  42065. */
  42066. _this._linkRefractionWithTransparency = false;
  42067. /**
  42068. * Specifies that the material will use the light map as a show map.
  42069. */
  42070. _this._useLightmapAsShadowmap = false;
  42071. /**
  42072. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42073. * makes the reflect vector face the model (under horizon).
  42074. */
  42075. _this._useHorizonOcclusion = true;
  42076. /**
  42077. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42078. * too much the area relying on ambient texture to define their ambient occlusion.
  42079. */
  42080. _this._useRadianceOcclusion = true;
  42081. /**
  42082. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42083. */
  42084. _this._useAlphaFromAlbedoTexture = false;
  42085. /**
  42086. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42087. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42088. */
  42089. _this._useSpecularOverAlpha = true;
  42090. /**
  42091. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42092. */
  42093. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  42094. /**
  42095. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42096. */
  42097. _this._useRoughnessFromMetallicTextureAlpha = true;
  42098. /**
  42099. * Specifies if the metallic texture contains the roughness information in its green channel.
  42100. */
  42101. _this._useRoughnessFromMetallicTextureGreen = false;
  42102. /**
  42103. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42104. */
  42105. _this._useMetallnessFromMetallicTextureBlue = false;
  42106. /**
  42107. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42108. */
  42109. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  42110. /**
  42111. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42112. */
  42113. _this._useAmbientInGrayScale = false;
  42114. /**
  42115. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42116. * The material will try to infer what glossiness each pixel should be.
  42117. */
  42118. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  42119. /**
  42120. * BJS is using an harcoded light falloff based on a manually sets up range.
  42121. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42122. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42123. */
  42124. _this._usePhysicalLightFalloff = true;
  42125. /**
  42126. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42127. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42128. */
  42129. _this._useRadianceOverAlpha = true;
  42130. /**
  42131. * Allows using an object space normal map (instead of tangent space).
  42132. */
  42133. _this._useObjectSpaceNormalMap = false;
  42134. /**
  42135. * Allows using the bump map in parallax mode.
  42136. */
  42137. _this._useParallax = false;
  42138. /**
  42139. * Allows using the bump map in parallax occlusion mode.
  42140. */
  42141. _this._useParallaxOcclusion = false;
  42142. /**
  42143. * Controls the scale bias of the parallax mode.
  42144. */
  42145. _this._parallaxScaleBias = 0.05;
  42146. /**
  42147. * If sets to true, disables all the lights affecting the material.
  42148. */
  42149. _this._disableLighting = false;
  42150. /**
  42151. * Number of Simultaneous lights allowed on the material.
  42152. */
  42153. _this._maxSimultaneousLights = 4;
  42154. /**
  42155. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  42156. */
  42157. _this._invertNormalMapX = false;
  42158. /**
  42159. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  42160. */
  42161. _this._invertNormalMapY = false;
  42162. /**
  42163. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42164. */
  42165. _this._twoSidedLighting = false;
  42166. /**
  42167. * Defines the alpha limits in alpha test mode.
  42168. */
  42169. _this._alphaCutOff = 0.4;
  42170. /**
  42171. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42172. */
  42173. _this._forceAlphaTest = false;
  42174. /**
  42175. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42176. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42177. */
  42178. _this._useAlphaFresnel = false;
  42179. /**
  42180. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42181. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42182. */
  42183. _this._useLinearAlphaFresnel = false;
  42184. /**
  42185. * The transparency mode of the material.
  42186. */
  42187. _this._transparencyMode = null;
  42188. /**
  42189. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  42190. * from cos thetav and roughness:
  42191. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  42192. */
  42193. _this._environmentBRDFTexture = null;
  42194. /**
  42195. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42196. */
  42197. _this._forceIrradianceInFragment = false;
  42198. /**
  42199. * Force normal to face away from face.
  42200. */
  42201. _this._forceNormalForward = false;
  42202. /**
  42203. * Stores the available render targets.
  42204. */
  42205. _this._renderTargets = new BABYLON.SmartArray(16);
  42206. /**
  42207. * Sets the global ambient color for the material used in lighting calculations.
  42208. */
  42209. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42210. /**
  42211. * If set to true, no lighting calculations will be applied.
  42212. */
  42213. _this._unlit = false;
  42214. // Setup the default processing configuration to the scene.
  42215. _this._attachImageProcessingConfiguration(null);
  42216. _this.getRenderTargetTextures = function () {
  42217. _this._renderTargets.reset();
  42218. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42219. _this._renderTargets.push(_this._reflectionTexture);
  42220. }
  42221. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42222. _this._renderTargets.push(_this._refractionTexture);
  42223. }
  42224. return _this._renderTargets;
  42225. };
  42226. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42227. return _this;
  42228. }
  42229. /**
  42230. * Attaches a new image processing configuration to the PBR Material.
  42231. * @param configuration
  42232. */
  42233. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42234. var _this = this;
  42235. if (configuration === this._imageProcessingConfiguration) {
  42236. return;
  42237. }
  42238. // Detaches observer.
  42239. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42240. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42241. }
  42242. // Pick the scene configuration if needed.
  42243. if (!configuration) {
  42244. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42245. }
  42246. else {
  42247. this._imageProcessingConfiguration = configuration;
  42248. }
  42249. // Attaches observer.
  42250. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42251. _this._markAllSubMeshesAsImageProcessingDirty();
  42252. });
  42253. };
  42254. /**
  42255. * Gets the name of the material class.
  42256. */
  42257. PBRBaseMaterial.prototype.getClassName = function () {
  42258. return "PBRBaseMaterial";
  42259. };
  42260. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  42261. /**
  42262. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  42263. */
  42264. get: function () {
  42265. return this._useLogarithmicDepth;
  42266. },
  42267. /**
  42268. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  42269. */
  42270. set: function (value) {
  42271. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42272. },
  42273. enumerable: true,
  42274. configurable: true
  42275. });
  42276. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  42277. /**
  42278. * Gets the current transparency mode.
  42279. */
  42280. get: function () {
  42281. return this._transparencyMode;
  42282. },
  42283. /**
  42284. * Sets the transparency mode of the material.
  42285. */
  42286. set: function (value) {
  42287. if (this._transparencyMode === value) {
  42288. return;
  42289. }
  42290. this._transparencyMode = value;
  42291. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  42292. this._markAllSubMeshesAsTexturesAndMiscDirty();
  42293. },
  42294. enumerable: true,
  42295. configurable: true
  42296. });
  42297. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  42298. /**
  42299. * Returns true if alpha blending should be disabled.
  42300. */
  42301. get: function () {
  42302. return (this._linkRefractionWithTransparency ||
  42303. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  42304. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  42305. },
  42306. enumerable: true,
  42307. configurable: true
  42308. });
  42309. /**
  42310. * Specifies whether or not this material should be rendered in alpha blend mode.
  42311. */
  42312. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  42313. if (this._disableAlphaBlending) {
  42314. return false;
  42315. }
  42316. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  42317. };
  42318. /**
  42319. * Specifies if the mesh will require alpha blending.
  42320. * @param mesh - BJS mesh.
  42321. */
  42322. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  42323. if (this._disableAlphaBlending) {
  42324. return false;
  42325. }
  42326. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  42327. };
  42328. /**
  42329. * Specifies whether or not this material should be rendered in alpha test mode.
  42330. */
  42331. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  42332. if (this._forceAlphaTest) {
  42333. return true;
  42334. }
  42335. if (this._linkRefractionWithTransparency) {
  42336. return false;
  42337. }
  42338. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  42339. };
  42340. /**
  42341. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  42342. */
  42343. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  42344. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  42345. };
  42346. /**
  42347. * Gets the texture used for the alpha test.
  42348. */
  42349. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  42350. return this._albedoTexture;
  42351. };
  42352. /**
  42353. * Specifies that the submesh is ready to be used.
  42354. * @param mesh - BJS mesh.
  42355. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  42356. * @param useInstances - Specifies that instances should be used.
  42357. * @returns - boolean indicating that the submesh is ready or not.
  42358. */
  42359. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42360. if (subMesh.effect && this.isFrozen) {
  42361. if (this._wasPreviouslyReady) {
  42362. return true;
  42363. }
  42364. }
  42365. if (!subMesh._materialDefines) {
  42366. subMesh._materialDefines = new PBRMaterialDefines();
  42367. }
  42368. var defines = subMesh._materialDefines;
  42369. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42370. if (defines._renderId === this.getScene().getRenderId()) {
  42371. return true;
  42372. }
  42373. }
  42374. var scene = this.getScene();
  42375. var engine = scene.getEngine();
  42376. if (defines._areTexturesDirty) {
  42377. if (scene.texturesEnabled) {
  42378. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42379. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  42380. return false;
  42381. }
  42382. }
  42383. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42384. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42385. return false;
  42386. }
  42387. }
  42388. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42389. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42390. return false;
  42391. }
  42392. }
  42393. var reflectionTexture = this._getReflectionTexture();
  42394. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42395. if (!reflectionTexture.isReadyOrNotBlocking()) {
  42396. return false;
  42397. }
  42398. }
  42399. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42400. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42401. return false;
  42402. }
  42403. }
  42404. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42405. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42406. return false;
  42407. }
  42408. }
  42409. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42410. if (this._metallicTexture) {
  42411. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  42412. return false;
  42413. }
  42414. }
  42415. else if (this._reflectivityTexture) {
  42416. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  42417. return false;
  42418. }
  42419. }
  42420. if (this._microSurfaceTexture) {
  42421. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  42422. return false;
  42423. }
  42424. }
  42425. }
  42426. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42427. // Bump texture cannot be not blocking.
  42428. if (!this._bumpTexture.isReady()) {
  42429. return false;
  42430. }
  42431. }
  42432. var refractionTexture = this._getRefractionTexture();
  42433. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42434. if (!refractionTexture.isReadyOrNotBlocking()) {
  42435. return false;
  42436. }
  42437. }
  42438. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42439. // This is blocking.
  42440. if (!this._environmentBRDFTexture.isReady()) {
  42441. return false;
  42442. }
  42443. }
  42444. }
  42445. }
  42446. if (defines._areImageProcessingDirty) {
  42447. if (!this._imageProcessingConfiguration.isReady()) {
  42448. return false;
  42449. }
  42450. }
  42451. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42452. mesh.createNormals(true);
  42453. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  42454. }
  42455. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  42456. if (effect) {
  42457. scene.resetCachedMaterial();
  42458. subMesh.setEffect(effect, defines);
  42459. this.buildUniformLayout();
  42460. }
  42461. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42462. return false;
  42463. }
  42464. defines._renderId = scene.getRenderId();
  42465. this._wasPreviouslyReady = true;
  42466. return true;
  42467. };
  42468. /**
  42469. * Specifies if the material uses metallic roughness workflow.
  42470. * @returns boolean specifiying if the material uses metallic roughness workflow.
  42471. */
  42472. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  42473. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  42474. return true;
  42475. }
  42476. return false;
  42477. };
  42478. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  42479. if (onCompiled === void 0) { onCompiled = null; }
  42480. if (onError === void 0) { onError = null; }
  42481. if (useInstances === void 0) { useInstances = null; }
  42482. if (useClipPlane === void 0) { useClipPlane = null; }
  42483. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  42484. if (!defines.isDirty) {
  42485. return null;
  42486. }
  42487. defines.markAsProcessed();
  42488. var scene = this.getScene();
  42489. var engine = scene.getEngine();
  42490. // Fallbacks
  42491. var fallbacks = new BABYLON.EffectFallbacks();
  42492. var fallbackRank = 0;
  42493. if (defines.USESPHERICALINVERTEX) {
  42494. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  42495. }
  42496. if (defines.FOG) {
  42497. fallbacks.addFallback(fallbackRank, "FOG");
  42498. }
  42499. if (defines.POINTSIZE) {
  42500. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  42501. }
  42502. if (defines.LOGARITHMICDEPTH) {
  42503. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  42504. }
  42505. if (defines.PARALLAX) {
  42506. fallbacks.addFallback(fallbackRank, "PARALLAX");
  42507. }
  42508. if (defines.PARALLAXOCCLUSION) {
  42509. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  42510. }
  42511. if (defines.ENVIRONMENTBRDF) {
  42512. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  42513. }
  42514. if (defines.TANGENT) {
  42515. fallbacks.addFallback(fallbackRank++, "TANGENT");
  42516. }
  42517. if (defines.BUMP) {
  42518. fallbacks.addFallback(fallbackRank++, "BUMP");
  42519. }
  42520. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  42521. if (defines.SPECULARTERM) {
  42522. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  42523. }
  42524. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  42525. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  42526. }
  42527. if (defines.LIGHTMAP) {
  42528. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  42529. }
  42530. if (defines.NORMAL) {
  42531. fallbacks.addFallback(fallbackRank++, "NORMAL");
  42532. }
  42533. if (defines.AMBIENT) {
  42534. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  42535. }
  42536. if (defines.EMISSIVE) {
  42537. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  42538. }
  42539. if (defines.VERTEXCOLOR) {
  42540. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  42541. }
  42542. if (defines.NUM_BONE_INFLUENCERS > 0) {
  42543. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  42544. }
  42545. if (defines.MORPHTARGETS) {
  42546. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  42547. }
  42548. //Attributes
  42549. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42550. if (defines.NORMAL) {
  42551. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42552. }
  42553. if (defines.TANGENT) {
  42554. attribs.push(BABYLON.VertexBuffer.TangentKind);
  42555. }
  42556. if (defines.UV1) {
  42557. attribs.push(BABYLON.VertexBuffer.UVKind);
  42558. }
  42559. if (defines.UV2) {
  42560. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42561. }
  42562. if (defines.VERTEXCOLOR) {
  42563. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42564. }
  42565. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42566. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42567. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42568. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  42569. "vFogInfos", "vFogColor", "pointSize",
  42570. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  42571. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42572. "mBones",
  42573. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  42574. "vLightingIntensity",
  42575. "logarithmicDepthConstant",
  42576. "vSphericalX", "vSphericalY", "vSphericalZ",
  42577. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  42578. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  42579. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  42580. "vTangentSpaceParams"
  42581. ];
  42582. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  42583. "bumpSampler", "lightmapSampler", "opacitySampler",
  42584. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  42585. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  42586. "microSurfaceSampler", "environmentBrdfSampler"];
  42587. var uniformBuffers = ["Material", "Scene"];
  42588. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42589. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42590. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42591. uniformsNames: uniforms,
  42592. uniformBuffersNames: uniformBuffers,
  42593. samplers: samplers,
  42594. defines: defines,
  42595. maxSimultaneousLights: this._maxSimultaneousLights
  42596. });
  42597. var join = defines.toString();
  42598. return engine.createEffect("pbr", {
  42599. attributes: attribs,
  42600. uniformsNames: uniforms,
  42601. uniformBuffersNames: uniformBuffers,
  42602. samplers: samplers,
  42603. defines: join,
  42604. fallbacks: fallbacks,
  42605. onCompiled: onCompiled,
  42606. onError: onError,
  42607. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42608. }, engine);
  42609. };
  42610. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  42611. if (useInstances === void 0) { useInstances = null; }
  42612. if (useClipPlane === void 0) { useClipPlane = null; }
  42613. var scene = this.getScene();
  42614. var engine = scene.getEngine();
  42615. // Lights
  42616. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42617. defines._needNormals = true;
  42618. // Textures
  42619. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  42620. if (defines._areTexturesDirty) {
  42621. defines._needUVs = false;
  42622. if (scene.texturesEnabled) {
  42623. if (scene.getEngine().getCaps().textureLOD) {
  42624. defines.LODBASEDMICROSFURACE = true;
  42625. }
  42626. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42627. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  42628. }
  42629. else {
  42630. defines.ALBEDO = false;
  42631. }
  42632. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42633. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42634. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  42635. }
  42636. else {
  42637. defines.AMBIENT = false;
  42638. }
  42639. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42640. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42641. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42642. }
  42643. else {
  42644. defines.OPACITY = false;
  42645. }
  42646. var reflectionTexture = this._getReflectionTexture();
  42647. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42648. defines.REFLECTION = true;
  42649. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  42650. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  42651. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  42652. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  42653. defines.INVERTCUBICMAP = true;
  42654. }
  42655. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  42656. switch (reflectionTexture.coordinatesMode) {
  42657. case BABYLON.Texture.CUBIC_MODE:
  42658. case BABYLON.Texture.INVCUBIC_MODE:
  42659. defines.REFLECTIONMAP_CUBIC = true;
  42660. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  42661. break;
  42662. case BABYLON.Texture.EXPLICIT_MODE:
  42663. defines.REFLECTIONMAP_EXPLICIT = true;
  42664. break;
  42665. case BABYLON.Texture.PLANAR_MODE:
  42666. defines.REFLECTIONMAP_PLANAR = true;
  42667. break;
  42668. case BABYLON.Texture.PROJECTION_MODE:
  42669. defines.REFLECTIONMAP_PROJECTION = true;
  42670. break;
  42671. case BABYLON.Texture.SKYBOX_MODE:
  42672. defines.REFLECTIONMAP_SKYBOX = true;
  42673. break;
  42674. case BABYLON.Texture.SPHERICAL_MODE:
  42675. defines.REFLECTIONMAP_SPHERICAL = true;
  42676. break;
  42677. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42678. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  42679. break;
  42680. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42681. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  42682. break;
  42683. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42684. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  42685. break;
  42686. }
  42687. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  42688. if (reflectionTexture.sphericalPolynomial) {
  42689. defines.USESPHERICALFROMREFLECTIONMAP = true;
  42690. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  42691. defines.USESPHERICALINVERTEX = false;
  42692. }
  42693. else {
  42694. defines.USESPHERICALINVERTEX = true;
  42695. }
  42696. }
  42697. }
  42698. }
  42699. else {
  42700. defines.REFLECTION = false;
  42701. defines.REFLECTIONMAP_3D = false;
  42702. defines.REFLECTIONMAP_SPHERICAL = false;
  42703. defines.REFLECTIONMAP_PLANAR = false;
  42704. defines.REFLECTIONMAP_CUBIC = false;
  42705. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42706. defines.REFLECTIONMAP_PROJECTION = false;
  42707. defines.REFLECTIONMAP_SKYBOX = false;
  42708. defines.REFLECTIONMAP_EXPLICIT = false;
  42709. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42710. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42711. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42712. defines.INVERTCUBICMAP = false;
  42713. defines.USESPHERICALFROMREFLECTIONMAP = false;
  42714. defines.USESPHERICALINVERTEX = false;
  42715. defines.REFLECTIONMAP_OPPOSITEZ = false;
  42716. defines.LODINREFLECTIONALPHA = false;
  42717. defines.GAMMAREFLECTION = false;
  42718. }
  42719. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42720. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42721. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42722. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  42723. }
  42724. else {
  42725. defines.LIGHTMAP = false;
  42726. }
  42727. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42728. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42729. }
  42730. else {
  42731. defines.EMISSIVE = false;
  42732. }
  42733. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42734. if (this._metallicTexture) {
  42735. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  42736. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  42737. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  42738. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  42739. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  42740. }
  42741. else if (this._reflectivityTexture) {
  42742. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  42743. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  42744. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  42745. }
  42746. else {
  42747. defines.REFLECTIVITY = false;
  42748. }
  42749. if (this._microSurfaceTexture) {
  42750. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  42751. }
  42752. else {
  42753. defines.MICROSURFACEMAP = false;
  42754. }
  42755. }
  42756. else {
  42757. defines.REFLECTIVITY = false;
  42758. defines.MICROSURFACEMAP = false;
  42759. }
  42760. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42762. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42763. defines.PARALLAX = true;
  42764. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  42765. }
  42766. else {
  42767. defines.PARALLAX = false;
  42768. }
  42769. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42770. }
  42771. else {
  42772. defines.BUMP = false;
  42773. }
  42774. var refractionTexture = this._getRefractionTexture();
  42775. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42776. defines.REFRACTION = true;
  42777. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  42778. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  42779. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  42780. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  42781. if (this._linkRefractionWithTransparency) {
  42782. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  42783. }
  42784. }
  42785. else {
  42786. defines.REFRACTION = false;
  42787. }
  42788. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42789. defines.ENVIRONMENTBRDF = true;
  42790. }
  42791. else {
  42792. defines.ENVIRONMENTBRDF = false;
  42793. }
  42794. if (this._shouldUseAlphaFromAlbedoTexture()) {
  42795. defines.ALPHAFROMALBEDO = true;
  42796. }
  42797. else {
  42798. defines.ALPHAFROMALBEDO = false;
  42799. }
  42800. }
  42801. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42802. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  42803. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  42804. if (!this.backFaceCulling && this._twoSidedLighting) {
  42805. defines.TWOSIDEDLIGHTING = true;
  42806. }
  42807. else {
  42808. defines.TWOSIDEDLIGHTING = false;
  42809. }
  42810. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  42811. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42812. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  42813. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  42814. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  42815. }
  42816. if (defines._areImageProcessingDirty) {
  42817. this._imageProcessingConfiguration.prepareDefines(defines);
  42818. }
  42819. defines.FORCENORMALFORWARD = this._forceNormalForward;
  42820. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  42821. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  42822. // Misc.
  42823. if (defines._areMiscDirty) {
  42824. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  42825. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42826. }
  42827. // Values that need to be evaluated on every frame
  42828. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  42829. // Attribs
  42830. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  42831. };
  42832. /**
  42833. * Force shader compilation
  42834. */
  42835. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  42836. var _this = this;
  42837. var localOptions = __assign({ clipPlane: false }, options);
  42838. var defines = new PBRMaterialDefines();
  42839. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  42840. if (effect.isReady()) {
  42841. if (onCompiled) {
  42842. onCompiled(this);
  42843. }
  42844. }
  42845. else {
  42846. effect.onCompileObservable.add(function () {
  42847. if (onCompiled) {
  42848. onCompiled(_this);
  42849. }
  42850. });
  42851. }
  42852. };
  42853. /**
  42854. * Initializes the uniform buffer layout for the shader.
  42855. */
  42856. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  42857. // Order is important !
  42858. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  42859. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  42860. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42861. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42862. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42863. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  42864. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  42865. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42866. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42867. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42868. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42869. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42870. this._uniformBuffer.addUniform("albedoMatrix", 16);
  42871. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42872. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42873. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42874. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42875. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  42876. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  42877. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42878. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42879. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42880. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42881. this._uniformBuffer.addUniform("vReflectionColor", 3);
  42882. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  42883. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  42884. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  42885. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  42886. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  42887. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42888. this._uniformBuffer.addUniform("pointSize", 1);
  42889. this._uniformBuffer.create();
  42890. };
  42891. /**
  42892. * Unbinds the textures.
  42893. */
  42894. PBRBaseMaterial.prototype.unbind = function () {
  42895. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42896. this._uniformBuffer.setTexture("reflectionSampler", null);
  42897. }
  42898. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42899. this._uniformBuffer.setTexture("refractionSampler", null);
  42900. }
  42901. _super.prototype.unbind.call(this);
  42902. };
  42903. /**
  42904. * Binds the submesh data.
  42905. * @param world - The world matrix.
  42906. * @param mesh - The BJS mesh.
  42907. * @param subMesh - A submesh of the BJS mesh.
  42908. */
  42909. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42910. var scene = this.getScene();
  42911. var defines = subMesh._materialDefines;
  42912. if (!defines) {
  42913. return;
  42914. }
  42915. var effect = subMesh.effect;
  42916. if (!effect) {
  42917. return;
  42918. }
  42919. this._activeEffect = effect;
  42920. // Matrices
  42921. this.bindOnlyWorldMatrix(world);
  42922. // Normal Matrix
  42923. if (defines.OBJECTSPACE_NORMALMAP) {
  42924. world.toNormalMatrix(this._normalMatrix);
  42925. this.bindOnlyNormalMatrix(this._normalMatrix);
  42926. }
  42927. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42928. // Bones
  42929. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  42930. var reflectionTexture = null;
  42931. if (mustRebind) {
  42932. this._uniformBuffer.bindToEffect(effect, "Material");
  42933. this.bindViewProjection(effect);
  42934. reflectionTexture = this._getReflectionTexture();
  42935. var refractionTexture = this._getRefractionTexture();
  42936. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42937. // Texture uniforms
  42938. if (scene.texturesEnabled) {
  42939. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42940. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  42941. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  42942. }
  42943. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42944. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  42945. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42946. }
  42947. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42948. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42949. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42950. }
  42951. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42952. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42953. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42954. if (reflectionTexture.boundingBoxSize) {
  42955. var cubeTexture = reflectionTexture;
  42956. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42957. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42958. }
  42959. var polynomials = reflectionTexture.sphericalPolynomial;
  42960. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42961. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42962. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42963. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42964. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42965. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42966. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42967. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42968. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42969. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42970. }
  42971. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42972. }
  42973. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42974. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42975. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42976. }
  42977. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42978. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42979. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42980. }
  42981. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42982. if (this._metallicTexture) {
  42983. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42984. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42985. }
  42986. else if (this._reflectivityTexture) {
  42987. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42988. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42989. }
  42990. if (this._microSurfaceTexture) {
  42991. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42992. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42993. }
  42994. }
  42995. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42996. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42997. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42998. if (scene._mirroredCameraPosition) {
  42999. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43000. }
  43001. else {
  43002. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43003. }
  43004. }
  43005. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43006. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  43007. var depth = 1.0;
  43008. if (!refractionTexture.isCube) {
  43009. if (refractionTexture.depth) {
  43010. depth = refractionTexture.depth;
  43011. }
  43012. }
  43013. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  43014. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  43015. }
  43016. }
  43017. // Point size
  43018. if (this.pointsCloud) {
  43019. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43020. }
  43021. // Colors
  43022. if (defines.METALLICWORKFLOW) {
  43023. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  43024. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  43025. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  43026. }
  43027. else {
  43028. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  43029. }
  43030. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  43031. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  43032. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  43033. // Misc
  43034. this._lightingInfos.x = this._directIntensity;
  43035. this._lightingInfos.y = this._emissiveIntensity;
  43036. this._lightingInfos.z = this._environmentIntensity;
  43037. this._lightingInfos.w = this._specularIntensity;
  43038. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  43039. }
  43040. // Textures
  43041. if (scene.texturesEnabled) {
  43042. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43043. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  43044. }
  43045. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43046. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  43047. }
  43048. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43049. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  43050. }
  43051. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43052. if (defines.LODBASEDMICROSFURACE) {
  43053. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  43054. }
  43055. else {
  43056. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  43057. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  43058. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  43059. }
  43060. }
  43061. if (defines.ENVIRONMENTBRDF) {
  43062. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  43063. }
  43064. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43065. if (defines.LODBASEDMICROSFURACE) {
  43066. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  43067. }
  43068. else {
  43069. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  43070. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  43071. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  43072. }
  43073. }
  43074. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43075. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  43076. }
  43077. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43078. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  43079. }
  43080. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43081. if (this._metallicTexture) {
  43082. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  43083. }
  43084. else if (this._reflectivityTexture) {
  43085. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  43086. }
  43087. if (this._microSurfaceTexture) {
  43088. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  43089. }
  43090. }
  43091. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43092. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  43093. }
  43094. }
  43095. // Clip plane
  43096. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  43097. // Colors
  43098. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  43099. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  43100. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  43101. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  43102. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43103. }
  43104. if (mustRebind || !this.isFrozen) {
  43105. // Lights
  43106. if (scene.lightsEnabled && !this._disableLighting) {
  43107. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  43108. }
  43109. // View
  43110. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  43111. this.bindView(effect);
  43112. }
  43113. // Fog
  43114. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  43115. // Morph targets
  43116. if (defines.NUM_MORPH_INFLUENCERS) {
  43117. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  43118. }
  43119. // image processing
  43120. this._imageProcessingConfiguration.bind(this._activeEffect);
  43121. // Log. depth
  43122. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  43123. }
  43124. this._uniformBuffer.update();
  43125. this._afterBind(mesh);
  43126. };
  43127. /**
  43128. * Returns the animatable textures.
  43129. * @returns - Array of animatable textures.
  43130. */
  43131. PBRBaseMaterial.prototype.getAnimatables = function () {
  43132. var results = [];
  43133. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  43134. results.push(this._albedoTexture);
  43135. }
  43136. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43137. results.push(this._ambientTexture);
  43138. }
  43139. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43140. results.push(this._opacityTexture);
  43141. }
  43142. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43143. results.push(this._reflectionTexture);
  43144. }
  43145. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43146. results.push(this._emissiveTexture);
  43147. }
  43148. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  43149. results.push(this._metallicTexture);
  43150. }
  43151. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  43152. results.push(this._reflectivityTexture);
  43153. }
  43154. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43155. results.push(this._bumpTexture);
  43156. }
  43157. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43158. results.push(this._lightmapTexture);
  43159. }
  43160. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43161. results.push(this._refractionTexture);
  43162. }
  43163. return results;
  43164. };
  43165. /**
  43166. * Returns the texture used for reflections.
  43167. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  43168. */
  43169. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  43170. if (this._reflectionTexture) {
  43171. return this._reflectionTexture;
  43172. }
  43173. return this.getScene().environmentTexture;
  43174. };
  43175. /**
  43176. * Returns the texture used for refraction or null if none is used.
  43177. * @returns - Refection texture if present. If no refraction texture and refraction
  43178. * is linked with transparency, returns environment texture. Otherwise, returns null.
  43179. */
  43180. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  43181. if (this._refractionTexture) {
  43182. return this._refractionTexture;
  43183. }
  43184. if (this._linkRefractionWithTransparency) {
  43185. return this.getScene().environmentTexture;
  43186. }
  43187. return null;
  43188. };
  43189. /**
  43190. * Disposes the resources of the material.
  43191. * @param forceDisposeEffect - Forces the disposal of effects.
  43192. * @param forceDisposeTextures - Forces the disposal of all textures.
  43193. */
  43194. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43195. if (forceDisposeTextures) {
  43196. if (this._albedoTexture) {
  43197. this._albedoTexture.dispose();
  43198. }
  43199. if (this._ambientTexture) {
  43200. this._ambientTexture.dispose();
  43201. }
  43202. if (this._opacityTexture) {
  43203. this._opacityTexture.dispose();
  43204. }
  43205. if (this._reflectionTexture) {
  43206. this._reflectionTexture.dispose();
  43207. }
  43208. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  43209. this._environmentBRDFTexture.dispose();
  43210. }
  43211. if (this._emissiveTexture) {
  43212. this._emissiveTexture.dispose();
  43213. }
  43214. if (this._metallicTexture) {
  43215. this._metallicTexture.dispose();
  43216. }
  43217. if (this._reflectivityTexture) {
  43218. this._reflectivityTexture.dispose();
  43219. }
  43220. if (this._bumpTexture) {
  43221. this._bumpTexture.dispose();
  43222. }
  43223. if (this._lightmapTexture) {
  43224. this._lightmapTexture.dispose();
  43225. }
  43226. if (this._refractionTexture) {
  43227. this._refractionTexture.dispose();
  43228. }
  43229. }
  43230. this._renderTargets.dispose();
  43231. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43232. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43233. }
  43234. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43235. };
  43236. /**
  43237. * Stores the reflectivity values based on metallic roughness workflow.
  43238. */
  43239. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  43240. __decorate([
  43241. BABYLON.serializeAsImageProcessingConfiguration()
  43242. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  43243. __decorate([
  43244. BABYLON.serialize()
  43245. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  43246. __decorate([
  43247. BABYLON.serialize()
  43248. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  43249. return PBRBaseMaterial;
  43250. }(BABYLON.PushMaterial));
  43251. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  43252. })(BABYLON || (BABYLON = {}));
  43253. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  43254. "use strict";
  43255. var BABYLON;
  43256. (function (BABYLON) {
  43257. /**
  43258. * The Physically based simple base material of BJS.
  43259. *
  43260. * This enables better naming and convention enforcements on top of the pbrMaterial.
  43261. * It is used as the base class for both the specGloss and metalRough conventions.
  43262. */
  43263. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  43264. __extends(PBRBaseSimpleMaterial, _super);
  43265. /**
  43266. * Instantiates a new PBRMaterial instance.
  43267. *
  43268. * @param name The material name
  43269. * @param scene The scene the material will be use in.
  43270. */
  43271. function PBRBaseSimpleMaterial(name, scene) {
  43272. var _this = _super.call(this, name, scene) || this;
  43273. /**
  43274. * Number of Simultaneous lights allowed on the material.
  43275. */
  43276. _this.maxSimultaneousLights = 4;
  43277. /**
  43278. * If sets to true, disables all the lights affecting the material.
  43279. */
  43280. _this.disableLighting = false;
  43281. /**
  43282. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43283. */
  43284. _this.invertNormalMapX = false;
  43285. /**
  43286. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43287. */
  43288. _this.invertNormalMapY = false;
  43289. /**
  43290. * Emissivie color used to self-illuminate the model.
  43291. */
  43292. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43293. /**
  43294. * Occlusion Channel Strenght.
  43295. */
  43296. _this.occlusionStrength = 1.0;
  43297. _this.useLightmapAsShadowmap = false;
  43298. _this._useAlphaFromAlbedoTexture = true;
  43299. _this._useAmbientInGrayScale = true;
  43300. return _this;
  43301. }
  43302. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  43303. /**
  43304. * Gets the current double sided mode.
  43305. */
  43306. get: function () {
  43307. return this._twoSidedLighting;
  43308. },
  43309. /**
  43310. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43311. */
  43312. set: function (value) {
  43313. if (this._twoSidedLighting === value) {
  43314. return;
  43315. }
  43316. this._twoSidedLighting = value;
  43317. this.backFaceCulling = !value;
  43318. this._markAllSubMeshesAsTexturesDirty();
  43319. },
  43320. enumerable: true,
  43321. configurable: true
  43322. });
  43323. /**
  43324. * Return the active textures of the material.
  43325. */
  43326. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  43327. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43328. if (this.environmentTexture) {
  43329. activeTextures.push(this.environmentTexture);
  43330. }
  43331. if (this.normalTexture) {
  43332. activeTextures.push(this.normalTexture);
  43333. }
  43334. if (this.emissiveTexture) {
  43335. activeTextures.push(this.emissiveTexture);
  43336. }
  43337. if (this.occlusionTexture) {
  43338. activeTextures.push(this.occlusionTexture);
  43339. }
  43340. if (this.lightmapTexture) {
  43341. activeTextures.push(this.lightmapTexture);
  43342. }
  43343. return activeTextures;
  43344. };
  43345. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  43346. if (_super.prototype.hasTexture.call(this, texture)) {
  43347. return true;
  43348. }
  43349. if (this.lightmapTexture === texture) {
  43350. return true;
  43351. }
  43352. return false;
  43353. };
  43354. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  43355. return "PBRBaseSimpleMaterial";
  43356. };
  43357. __decorate([
  43358. BABYLON.serialize(),
  43359. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43360. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  43361. __decorate([
  43362. BABYLON.serialize(),
  43363. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43364. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  43365. __decorate([
  43366. BABYLON.serializeAsTexture(),
  43367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  43368. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  43369. __decorate([
  43370. BABYLON.serialize(),
  43371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43372. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  43373. __decorate([
  43374. BABYLON.serialize(),
  43375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43376. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  43377. __decorate([
  43378. BABYLON.serializeAsTexture(),
  43379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  43380. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  43381. __decorate([
  43382. BABYLON.serializeAsColor3("emissive"),
  43383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43384. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  43385. __decorate([
  43386. BABYLON.serializeAsTexture(),
  43387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43388. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  43389. __decorate([
  43390. BABYLON.serialize(),
  43391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  43392. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  43393. __decorate([
  43394. BABYLON.serializeAsTexture(),
  43395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  43396. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  43397. __decorate([
  43398. BABYLON.serialize(),
  43399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  43400. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  43401. __decorate([
  43402. BABYLON.serialize()
  43403. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  43404. __decorate([
  43405. BABYLON.serializeAsTexture(),
  43406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43407. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  43408. __decorate([
  43409. BABYLON.serialize(),
  43410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43411. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43412. return PBRBaseSimpleMaterial;
  43413. }(BABYLON.PBRBaseMaterial));
  43414. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  43415. })(BABYLON || (BABYLON = {}));
  43416. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  43417. "use strict";
  43418. var BABYLON;
  43419. (function (BABYLON) {
  43420. /**
  43421. * The Physically based material of BJS.
  43422. *
  43423. * This offers the main features of a standard PBR material.
  43424. * For more information, please refer to the documentation :
  43425. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43426. */
  43427. var PBRMaterial = /** @class */ (function (_super) {
  43428. __extends(PBRMaterial, _super);
  43429. /**
  43430. * Instantiates a new PBRMaterial instance.
  43431. *
  43432. * @param name The material name
  43433. * @param scene The scene the material will be use in.
  43434. */
  43435. function PBRMaterial(name, scene) {
  43436. var _this = _super.call(this, name, scene) || this;
  43437. /**
  43438. * Intensity of the direct lights e.g. the four lights available in your scene.
  43439. * This impacts both the direct diffuse and specular highlights.
  43440. */
  43441. _this.directIntensity = 1.0;
  43442. /**
  43443. * Intensity of the emissive part of the material.
  43444. * This helps controlling the emissive effect without modifying the emissive color.
  43445. */
  43446. _this.emissiveIntensity = 1.0;
  43447. /**
  43448. * Intensity of the environment e.g. how much the environment will light the object
  43449. * either through harmonics for rough material or through the refelction for shiny ones.
  43450. */
  43451. _this.environmentIntensity = 1.0;
  43452. /**
  43453. * This is a special control allowing the reduction of the specular highlights coming from the
  43454. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43455. */
  43456. _this.specularIntensity = 1.0;
  43457. /**
  43458. * Debug Control allowing disabling the bump map on this material.
  43459. */
  43460. _this.disableBumpMap = false;
  43461. /**
  43462. * AKA Occlusion Texture Intensity in other nomenclature.
  43463. */
  43464. _this.ambientTextureStrength = 1.0;
  43465. /**
  43466. * The color of a material in ambient lighting.
  43467. */
  43468. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43469. /**
  43470. * AKA Diffuse Color in other nomenclature.
  43471. */
  43472. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  43473. /**
  43474. * AKA Specular Color in other nomenclature.
  43475. */
  43476. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43477. /**
  43478. * The color reflected from the material.
  43479. */
  43480. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  43481. /**
  43482. * The color emitted from the material.
  43483. */
  43484. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43485. /**
  43486. * AKA Glossiness in other nomenclature.
  43487. */
  43488. _this.microSurface = 1.0;
  43489. /**
  43490. * source material index of refraction (IOR)' / 'destination material IOR.
  43491. */
  43492. _this.indexOfRefraction = 0.66;
  43493. /**
  43494. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43495. */
  43496. _this.invertRefractionY = false;
  43497. /**
  43498. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43499. * Materials half opaque for instance using refraction could benefit from this control.
  43500. */
  43501. _this.linkRefractionWithTransparency = false;
  43502. _this.useLightmapAsShadowmap = false;
  43503. /**
  43504. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43505. */
  43506. _this.useAlphaFromAlbedoTexture = false;
  43507. /**
  43508. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43509. */
  43510. _this.forceAlphaTest = false;
  43511. /**
  43512. * Defines the alpha limits in alpha test mode.
  43513. */
  43514. _this.alphaCutOff = 0.4;
  43515. /**
  43516. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43517. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43518. */
  43519. _this.useSpecularOverAlpha = true;
  43520. /**
  43521. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43522. */
  43523. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  43524. /**
  43525. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43526. */
  43527. _this.useRoughnessFromMetallicTextureAlpha = true;
  43528. /**
  43529. * Specifies if the metallic texture contains the roughness information in its green channel.
  43530. */
  43531. _this.useRoughnessFromMetallicTextureGreen = false;
  43532. /**
  43533. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43534. */
  43535. _this.useMetallnessFromMetallicTextureBlue = false;
  43536. /**
  43537. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43538. */
  43539. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  43540. /**
  43541. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43542. */
  43543. _this.useAmbientInGrayScale = false;
  43544. /**
  43545. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43546. * The material will try to infer what glossiness each pixel should be.
  43547. */
  43548. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  43549. /**
  43550. * BJS is using an harcoded light falloff based on a manually sets up range.
  43551. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43552. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43553. */
  43554. _this.usePhysicalLightFalloff = true;
  43555. /**
  43556. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43557. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43558. */
  43559. _this.useRadianceOverAlpha = true;
  43560. /**
  43561. * Allows using an object space normal map (instead of tangent space).
  43562. */
  43563. _this.useObjectSpaceNormalMap = false;
  43564. /**
  43565. * Allows using the bump map in parallax mode.
  43566. */
  43567. _this.useParallax = false;
  43568. /**
  43569. * Allows using the bump map in parallax occlusion mode.
  43570. */
  43571. _this.useParallaxOcclusion = false;
  43572. /**
  43573. * Controls the scale bias of the parallax mode.
  43574. */
  43575. _this.parallaxScaleBias = 0.05;
  43576. /**
  43577. * If sets to true, disables all the lights affecting the material.
  43578. */
  43579. _this.disableLighting = false;
  43580. /**
  43581. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43582. */
  43583. _this.forceIrradianceInFragment = false;
  43584. /**
  43585. * Number of Simultaneous lights allowed on the material.
  43586. */
  43587. _this.maxSimultaneousLights = 4;
  43588. /**
  43589. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43590. */
  43591. _this.invertNormalMapX = false;
  43592. /**
  43593. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43594. */
  43595. _this.invertNormalMapY = false;
  43596. /**
  43597. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43598. */
  43599. _this.twoSidedLighting = false;
  43600. /**
  43601. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43602. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43603. */
  43604. _this.useAlphaFresnel = false;
  43605. /**
  43606. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43607. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43608. */
  43609. _this.useLinearAlphaFresnel = false;
  43610. /**
  43611. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43612. * And/Or occlude the blended part.
  43613. */
  43614. _this.environmentBRDFTexture = null;
  43615. /**
  43616. * Force normal to face away from face.
  43617. */
  43618. _this.forceNormalForward = false;
  43619. /**
  43620. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43621. * makes the reflect vector face the model (under horizon).
  43622. */
  43623. _this.useHorizonOcclusion = true;
  43624. /**
  43625. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43626. * too much the area relying on ambient texture to define their ambient occlusion.
  43627. */
  43628. _this.useRadianceOcclusion = true;
  43629. /**
  43630. * If set to true, no lighting calculations will be applied.
  43631. */
  43632. _this.unlit = false;
  43633. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43634. return _this;
  43635. }
  43636. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  43637. /**
  43638. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  43639. */
  43640. get: function () {
  43641. return this._PBRMATERIAL_OPAQUE;
  43642. },
  43643. enumerable: true,
  43644. configurable: true
  43645. });
  43646. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  43647. /**
  43648. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43649. */
  43650. get: function () {
  43651. return this._PBRMATERIAL_ALPHATEST;
  43652. },
  43653. enumerable: true,
  43654. configurable: true
  43655. });
  43656. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  43657. /**
  43658. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43659. */
  43660. get: function () {
  43661. return this._PBRMATERIAL_ALPHABLEND;
  43662. },
  43663. enumerable: true,
  43664. configurable: true
  43665. });
  43666. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  43667. /**
  43668. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43669. * They are also discarded below the alpha cutoff threshold to improve performances.
  43670. */
  43671. get: function () {
  43672. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  43673. },
  43674. enumerable: true,
  43675. configurable: true
  43676. });
  43677. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  43678. /**
  43679. * Gets the image processing configuration used either in this material.
  43680. */
  43681. get: function () {
  43682. return this._imageProcessingConfiguration;
  43683. },
  43684. /**
  43685. * Sets the Default image processing configuration used either in the this material.
  43686. *
  43687. * If sets to null, the scene one is in use.
  43688. */
  43689. set: function (value) {
  43690. this._attachImageProcessingConfiguration(value);
  43691. // Ensure the effect will be rebuilt.
  43692. this._markAllSubMeshesAsTexturesDirty();
  43693. },
  43694. enumerable: true,
  43695. configurable: true
  43696. });
  43697. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  43698. /**
  43699. * Gets wether the color curves effect is enabled.
  43700. */
  43701. get: function () {
  43702. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43703. },
  43704. /**
  43705. * Sets wether the color curves effect is enabled.
  43706. */
  43707. set: function (value) {
  43708. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43709. },
  43710. enumerable: true,
  43711. configurable: true
  43712. });
  43713. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  43714. /**
  43715. * Gets wether the color grading effect is enabled.
  43716. */
  43717. get: function () {
  43718. return this.imageProcessingConfiguration.colorGradingEnabled;
  43719. },
  43720. /**
  43721. * Gets wether the color grading effect is enabled.
  43722. */
  43723. set: function (value) {
  43724. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43725. },
  43726. enumerable: true,
  43727. configurable: true
  43728. });
  43729. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  43730. /**
  43731. * Gets wether tonemapping is enabled or not.
  43732. */
  43733. get: function () {
  43734. return this._imageProcessingConfiguration.toneMappingEnabled;
  43735. },
  43736. /**
  43737. * Sets wether tonemapping is enabled or not
  43738. */
  43739. set: function (value) {
  43740. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43741. },
  43742. enumerable: true,
  43743. configurable: true
  43744. });
  43745. ;
  43746. ;
  43747. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  43748. /**
  43749. * The camera exposure used on this material.
  43750. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43751. * This corresponds to a photographic exposure.
  43752. */
  43753. get: function () {
  43754. return this._imageProcessingConfiguration.exposure;
  43755. },
  43756. /**
  43757. * The camera exposure used on this material.
  43758. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43759. * This corresponds to a photographic exposure.
  43760. */
  43761. set: function (value) {
  43762. this._imageProcessingConfiguration.exposure = value;
  43763. },
  43764. enumerable: true,
  43765. configurable: true
  43766. });
  43767. ;
  43768. ;
  43769. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  43770. /**
  43771. * Gets The camera contrast used on this material.
  43772. */
  43773. get: function () {
  43774. return this._imageProcessingConfiguration.contrast;
  43775. },
  43776. /**
  43777. * Sets The camera contrast used on this material.
  43778. */
  43779. set: function (value) {
  43780. this._imageProcessingConfiguration.contrast = value;
  43781. },
  43782. enumerable: true,
  43783. configurable: true
  43784. });
  43785. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  43786. /**
  43787. * Gets the Color Grading 2D Lookup Texture.
  43788. */
  43789. get: function () {
  43790. return this._imageProcessingConfiguration.colorGradingTexture;
  43791. },
  43792. /**
  43793. * Sets the Color Grading 2D Lookup Texture.
  43794. */
  43795. set: function (value) {
  43796. this._imageProcessingConfiguration.colorGradingTexture = value;
  43797. },
  43798. enumerable: true,
  43799. configurable: true
  43800. });
  43801. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  43802. /**
  43803. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43804. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43805. * 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;
  43806. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43807. */
  43808. get: function () {
  43809. return this._imageProcessingConfiguration.colorCurves;
  43810. },
  43811. /**
  43812. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43813. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43814. * 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;
  43815. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43816. */
  43817. set: function (value) {
  43818. this._imageProcessingConfiguration.colorCurves = value;
  43819. },
  43820. enumerable: true,
  43821. configurable: true
  43822. });
  43823. /**
  43824. * Returns the name of this material class.
  43825. */
  43826. PBRMaterial.prototype.getClassName = function () {
  43827. return "PBRMaterial";
  43828. };
  43829. /**
  43830. * Returns an array of the actively used textures.
  43831. * @returns - Array of BaseTextures
  43832. */
  43833. PBRMaterial.prototype.getActiveTextures = function () {
  43834. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43835. if (this._albedoTexture) {
  43836. activeTextures.push(this._albedoTexture);
  43837. }
  43838. if (this._ambientTexture) {
  43839. activeTextures.push(this._ambientTexture);
  43840. }
  43841. if (this._opacityTexture) {
  43842. activeTextures.push(this._opacityTexture);
  43843. }
  43844. if (this._reflectionTexture) {
  43845. activeTextures.push(this._reflectionTexture);
  43846. }
  43847. if (this._emissiveTexture) {
  43848. activeTextures.push(this._emissiveTexture);
  43849. }
  43850. if (this._reflectivityTexture) {
  43851. activeTextures.push(this._reflectivityTexture);
  43852. }
  43853. if (this._metallicTexture) {
  43854. activeTextures.push(this._metallicTexture);
  43855. }
  43856. if (this._microSurfaceTexture) {
  43857. activeTextures.push(this._microSurfaceTexture);
  43858. }
  43859. if (this._bumpTexture) {
  43860. activeTextures.push(this._bumpTexture);
  43861. }
  43862. if (this._lightmapTexture) {
  43863. activeTextures.push(this._lightmapTexture);
  43864. }
  43865. if (this._refractionTexture) {
  43866. activeTextures.push(this._refractionTexture);
  43867. }
  43868. return activeTextures;
  43869. };
  43870. /**
  43871. * Checks to see if a texture is used in the material.
  43872. * @param texture - Base texture to use.
  43873. * @returns - Boolean specifying if a texture is used in the material.
  43874. */
  43875. PBRMaterial.prototype.hasTexture = function (texture) {
  43876. if (_super.prototype.hasTexture.call(this, texture)) {
  43877. return true;
  43878. }
  43879. if (this._albedoTexture === texture) {
  43880. return true;
  43881. }
  43882. if (this._ambientTexture === texture) {
  43883. return true;
  43884. }
  43885. if (this._opacityTexture === texture) {
  43886. return true;
  43887. }
  43888. if (this._reflectionTexture === texture) {
  43889. return true;
  43890. }
  43891. if (this._reflectivityTexture === texture) {
  43892. return true;
  43893. }
  43894. if (this._metallicTexture === texture) {
  43895. return true;
  43896. }
  43897. if (this._microSurfaceTexture === texture) {
  43898. return true;
  43899. }
  43900. if (this._bumpTexture === texture) {
  43901. return true;
  43902. }
  43903. if (this._lightmapTexture === texture) {
  43904. return true;
  43905. }
  43906. if (this._refractionTexture === texture) {
  43907. return true;
  43908. }
  43909. return false;
  43910. };
  43911. /**
  43912. * Makes a duplicate of the current material.
  43913. * @param name - name to use for the new material.
  43914. */
  43915. PBRMaterial.prototype.clone = function (name) {
  43916. var _this = this;
  43917. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  43918. clone.id = name;
  43919. clone.name = name;
  43920. return clone;
  43921. };
  43922. /**
  43923. * Serializes this PBR Material.
  43924. * @returns - An object with the serialized material.
  43925. */
  43926. PBRMaterial.prototype.serialize = function () {
  43927. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43928. serializationObject.customType = "BABYLON.PBRMaterial";
  43929. return serializationObject;
  43930. };
  43931. // Statics
  43932. /**
  43933. * Parses a PBR Material from a serialized object.
  43934. * @param source - Serialized object.
  43935. * @param scene - BJS scene instance.
  43936. * @param rootUrl - url for the scene object
  43937. * @returns - PBRMaterial
  43938. */
  43939. PBRMaterial.Parse = function (source, scene, rootUrl) {
  43940. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  43941. };
  43942. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  43943. /**
  43944. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43945. */
  43946. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43947. /**
  43948. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43949. */
  43950. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43951. /**
  43952. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43953. * They are also discarded below the alpha cutoff threshold to improve performances.
  43954. */
  43955. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43956. __decorate([
  43957. BABYLON.serialize(),
  43958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43959. ], PBRMaterial.prototype, "directIntensity", void 0);
  43960. __decorate([
  43961. BABYLON.serialize(),
  43962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43963. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43964. __decorate([
  43965. BABYLON.serialize(),
  43966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43967. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43968. __decorate([
  43969. BABYLON.serialize(),
  43970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43971. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43972. __decorate([
  43973. BABYLON.serialize(),
  43974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43975. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43976. __decorate([
  43977. BABYLON.serializeAsTexture(),
  43978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43979. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43980. __decorate([
  43981. BABYLON.serializeAsTexture(),
  43982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43983. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43984. __decorate([
  43985. BABYLON.serialize(),
  43986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43987. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43988. __decorate([
  43989. BABYLON.serializeAsTexture(),
  43990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43991. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43992. __decorate([
  43993. BABYLON.serializeAsTexture(),
  43994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43995. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43996. __decorate([
  43997. BABYLON.serializeAsTexture(),
  43998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43999. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  44000. __decorate([
  44001. BABYLON.serializeAsTexture(),
  44002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44003. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  44004. __decorate([
  44005. BABYLON.serializeAsTexture(),
  44006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44007. ], PBRMaterial.prototype, "metallicTexture", void 0);
  44008. __decorate([
  44009. BABYLON.serialize(),
  44010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44011. ], PBRMaterial.prototype, "metallic", void 0);
  44012. __decorate([
  44013. BABYLON.serialize(),
  44014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44015. ], PBRMaterial.prototype, "roughness", void 0);
  44016. __decorate([
  44017. BABYLON.serializeAsTexture(),
  44018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44019. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  44020. __decorate([
  44021. BABYLON.serializeAsTexture(),
  44022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44023. ], PBRMaterial.prototype, "bumpTexture", void 0);
  44024. __decorate([
  44025. BABYLON.serializeAsTexture(),
  44026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44027. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  44028. __decorate([
  44029. BABYLON.serializeAsTexture(),
  44030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44031. ], PBRMaterial.prototype, "refractionTexture", void 0);
  44032. __decorate([
  44033. BABYLON.serializeAsColor3("ambient"),
  44034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44035. ], PBRMaterial.prototype, "ambientColor", void 0);
  44036. __decorate([
  44037. BABYLON.serializeAsColor3("albedo"),
  44038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44039. ], PBRMaterial.prototype, "albedoColor", void 0);
  44040. __decorate([
  44041. BABYLON.serializeAsColor3("reflectivity"),
  44042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44043. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  44044. __decorate([
  44045. BABYLON.serializeAsColor3("reflection"),
  44046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44047. ], PBRMaterial.prototype, "reflectionColor", void 0);
  44048. __decorate([
  44049. BABYLON.serializeAsColor3("emissive"),
  44050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44051. ], PBRMaterial.prototype, "emissiveColor", void 0);
  44052. __decorate([
  44053. BABYLON.serialize(),
  44054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44055. ], PBRMaterial.prototype, "microSurface", void 0);
  44056. __decorate([
  44057. BABYLON.serialize(),
  44058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44059. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  44060. __decorate([
  44061. BABYLON.serialize(),
  44062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44063. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  44064. __decorate([
  44065. BABYLON.serialize(),
  44066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44067. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  44068. __decorate([
  44069. BABYLON.serialize(),
  44070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44071. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44072. __decorate([
  44073. BABYLON.serialize(),
  44074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44075. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  44076. __decorate([
  44077. BABYLON.serialize(),
  44078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44079. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  44080. __decorate([
  44081. BABYLON.serialize(),
  44082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44083. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  44084. __decorate([
  44085. BABYLON.serialize(),
  44086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44087. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  44088. __decorate([
  44089. BABYLON.serialize(),
  44090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44091. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  44092. __decorate([
  44093. BABYLON.serialize(),
  44094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44095. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  44096. __decorate([
  44097. BABYLON.serialize(),
  44098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44099. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  44100. __decorate([
  44101. BABYLON.serialize(),
  44102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44103. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  44104. __decorate([
  44105. BABYLON.serialize(),
  44106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44107. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  44108. __decorate([
  44109. BABYLON.serialize(),
  44110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44111. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  44112. __decorate([
  44113. BABYLON.serialize(),
  44114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44115. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  44116. __decorate([
  44117. BABYLON.serialize(),
  44118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44119. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  44120. __decorate([
  44121. BABYLON.serialize(),
  44122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44123. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  44124. __decorate([
  44125. BABYLON.serialize(),
  44126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44127. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44128. __decorate([
  44129. BABYLON.serialize(),
  44130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44131. ], PBRMaterial.prototype, "useParallax", void 0);
  44132. __decorate([
  44133. BABYLON.serialize(),
  44134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44135. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  44136. __decorate([
  44137. BABYLON.serialize(),
  44138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44139. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  44140. __decorate([
  44141. BABYLON.serialize(),
  44142. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44143. ], PBRMaterial.prototype, "disableLighting", void 0);
  44144. __decorate([
  44145. BABYLON.serialize(),
  44146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44147. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  44148. __decorate([
  44149. BABYLON.serialize(),
  44150. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44151. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  44152. __decorate([
  44153. BABYLON.serialize(),
  44154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44155. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  44156. __decorate([
  44157. BABYLON.serialize(),
  44158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44159. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  44160. __decorate([
  44161. BABYLON.serialize(),
  44162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44163. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  44164. __decorate([
  44165. BABYLON.serialize(),
  44166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44167. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  44168. __decorate([
  44169. BABYLON.serialize(),
  44170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44171. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  44172. __decorate([
  44173. BABYLON.serializeAsTexture(),
  44174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44175. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  44176. __decorate([
  44177. BABYLON.serialize(),
  44178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44179. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  44180. __decorate([
  44181. BABYLON.serialize(),
  44182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44183. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  44184. __decorate([
  44185. BABYLON.serialize(),
  44186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44187. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  44188. __decorate([
  44189. BABYLON.serialize(),
  44190. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44191. ], PBRMaterial.prototype, "unlit", void 0);
  44192. return PBRMaterial;
  44193. }(BABYLON.PBRBaseMaterial));
  44194. BABYLON.PBRMaterial = PBRMaterial;
  44195. })(BABYLON || (BABYLON = {}));
  44196. //# sourceMappingURL=babylon.pbrMaterial.js.map
  44197. "use strict";
  44198. var BABYLON;
  44199. (function (BABYLON) {
  44200. /**
  44201. * The PBR material of BJS following the metal roughness convention.
  44202. *
  44203. * This fits to the PBR convention in the GLTF definition:
  44204. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  44205. */
  44206. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  44207. __extends(PBRMetallicRoughnessMaterial, _super);
  44208. /**
  44209. * Instantiates a new PBRMetalRoughnessMaterial instance.
  44210. *
  44211. * @param name The material name
  44212. * @param scene The scene the material will be use in.
  44213. */
  44214. function PBRMetallicRoughnessMaterial(name, scene) {
  44215. var _this = _super.call(this, name, scene) || this;
  44216. _this._useRoughnessFromMetallicTextureAlpha = false;
  44217. _this._useRoughnessFromMetallicTextureGreen = true;
  44218. _this._useMetallnessFromMetallicTextureBlue = true;
  44219. _this.metallic = 1.0;
  44220. _this.roughness = 1.0;
  44221. return _this;
  44222. }
  44223. /**
  44224. * Return the currrent class name of the material.
  44225. */
  44226. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  44227. return "PBRMetallicRoughnessMaterial";
  44228. };
  44229. /**
  44230. * Return the active textures of the material.
  44231. */
  44232. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  44233. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44234. if (this.baseTexture) {
  44235. activeTextures.push(this.baseTexture);
  44236. }
  44237. if (this.metallicRoughnessTexture) {
  44238. activeTextures.push(this.metallicRoughnessTexture);
  44239. }
  44240. return activeTextures;
  44241. };
  44242. /**
  44243. * Checks to see if a texture is used in the material.
  44244. * @param texture - Base texture to use.
  44245. * @returns - Boolean specifying if a texture is used in the material.
  44246. */
  44247. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  44248. if (_super.prototype.hasTexture.call(this, texture)) {
  44249. return true;
  44250. }
  44251. if (this.baseTexture === texture) {
  44252. return true;
  44253. }
  44254. if (this.metallicRoughnessTexture === texture) {
  44255. return true;
  44256. }
  44257. return false;
  44258. };
  44259. /**
  44260. * Makes a duplicate of the current material.
  44261. * @param name - name to use for the new material.
  44262. */
  44263. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  44264. var _this = this;
  44265. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  44266. clone.id = name;
  44267. clone.name = name;
  44268. return clone;
  44269. };
  44270. /**
  44271. * Serialize the material to a parsable JSON object.
  44272. */
  44273. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  44274. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44275. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  44276. return serializationObject;
  44277. };
  44278. /**
  44279. * Parses a JSON object correponding to the serialize function.
  44280. */
  44281. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  44282. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  44283. };
  44284. __decorate([
  44285. BABYLON.serializeAsColor3(),
  44286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  44287. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  44288. __decorate([
  44289. BABYLON.serializeAsTexture(),
  44290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  44291. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  44292. __decorate([
  44293. BABYLON.serialize(),
  44294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44295. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  44296. __decorate([
  44297. BABYLON.serialize(),
  44298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44299. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  44300. __decorate([
  44301. BABYLON.serializeAsTexture(),
  44302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  44303. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  44304. return PBRMetallicRoughnessMaterial;
  44305. }(BABYLON.PBRBaseSimpleMaterial));
  44306. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  44307. })(BABYLON || (BABYLON = {}));
  44308. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  44309. "use strict";
  44310. var BABYLON;
  44311. (function (BABYLON) {
  44312. /**
  44313. * The PBR material of BJS following the specular glossiness convention.
  44314. *
  44315. * This fits to the PBR convention in the GLTF definition:
  44316. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  44317. */
  44318. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  44319. __extends(PBRSpecularGlossinessMaterial, _super);
  44320. /**
  44321. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  44322. *
  44323. * @param name The material name
  44324. * @param scene The scene the material will be use in.
  44325. */
  44326. function PBRSpecularGlossinessMaterial(name, scene) {
  44327. var _this = _super.call(this, name, scene) || this;
  44328. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  44329. return _this;
  44330. }
  44331. /**
  44332. * Return the currrent class name of the material.
  44333. */
  44334. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  44335. return "PBRSpecularGlossinessMaterial";
  44336. };
  44337. /**
  44338. * Return the active textures of the material.
  44339. */
  44340. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  44341. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44342. if (this.diffuseTexture) {
  44343. activeTextures.push(this.diffuseTexture);
  44344. }
  44345. if (this.specularGlossinessTexture) {
  44346. activeTextures.push(this.specularGlossinessTexture);
  44347. }
  44348. return activeTextures;
  44349. };
  44350. /**
  44351. * Checks to see if a texture is used in the material.
  44352. * @param texture - Base texture to use.
  44353. * @returns - Boolean specifying if a texture is used in the material.
  44354. */
  44355. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  44356. if (_super.prototype.hasTexture.call(this, texture)) {
  44357. return true;
  44358. }
  44359. if (this.diffuseTexture === texture) {
  44360. return true;
  44361. }
  44362. if (this.specularGlossinessTexture === texture) {
  44363. return true;
  44364. }
  44365. return false;
  44366. };
  44367. /**
  44368. * Makes a duplicate of the current material.
  44369. * @param name - name to use for the new material.
  44370. */
  44371. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  44372. var _this = this;
  44373. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  44374. clone.id = name;
  44375. clone.name = name;
  44376. return clone;
  44377. };
  44378. /**
  44379. * Serialize the material to a parsable JSON object.
  44380. */
  44381. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  44382. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44383. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  44384. return serializationObject;
  44385. };
  44386. /**
  44387. * Parses a JSON object correponding to the serialize function.
  44388. */
  44389. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  44390. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  44391. };
  44392. __decorate([
  44393. BABYLON.serializeAsColor3("diffuse"),
  44394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  44395. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  44396. __decorate([
  44397. BABYLON.serializeAsTexture(),
  44398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  44399. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  44400. __decorate([
  44401. BABYLON.serializeAsColor3("specular"),
  44402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  44403. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  44404. __decorate([
  44405. BABYLON.serialize(),
  44406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  44407. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  44408. __decorate([
  44409. BABYLON.serializeAsTexture(),
  44410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  44411. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  44412. return PBRSpecularGlossinessMaterial;
  44413. }(BABYLON.PBRBaseSimpleMaterial));
  44414. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  44415. })(BABYLON || (BABYLON = {}));
  44416. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  44417. "use strict";
  44418. var BABYLON;
  44419. (function (BABYLON) {
  44420. BABYLON.CameraInputTypes = {};
  44421. var CameraInputsManager = /** @class */ (function () {
  44422. function CameraInputsManager(camera) {
  44423. this.attached = {};
  44424. this.camera = camera;
  44425. this.checkInputs = function () { };
  44426. }
  44427. /**
  44428. * Add an input method to a camera.
  44429. * builtin inputs example: camera.inputs.addGamepad();
  44430. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  44431. * @param input camera input method
  44432. */
  44433. CameraInputsManager.prototype.add = function (input) {
  44434. var type = input.getSimpleName();
  44435. if (this.attached[type]) {
  44436. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  44437. return;
  44438. }
  44439. this.attached[type] = input;
  44440. input.camera = this.camera;
  44441. //for checkInputs, we are dynamically creating a function
  44442. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  44443. if (input.checkInputs) {
  44444. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  44445. }
  44446. if (this.attachedElement) {
  44447. input.attachControl(this.attachedElement);
  44448. }
  44449. };
  44450. /**
  44451. * Remove a specific input method from a camera
  44452. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  44453. * @param inputToRemove camera input method
  44454. */
  44455. CameraInputsManager.prototype.remove = function (inputToRemove) {
  44456. for (var cam in this.attached) {
  44457. var input = this.attached[cam];
  44458. if (input === inputToRemove) {
  44459. input.detachControl(this.attachedElement);
  44460. input.camera = null;
  44461. delete this.attached[cam];
  44462. this.rebuildInputCheck();
  44463. }
  44464. }
  44465. };
  44466. CameraInputsManager.prototype.removeByType = function (inputType) {
  44467. for (var cam in this.attached) {
  44468. var input = this.attached[cam];
  44469. if (input.getClassName() === inputType) {
  44470. input.detachControl(this.attachedElement);
  44471. input.camera = null;
  44472. delete this.attached[cam];
  44473. this.rebuildInputCheck();
  44474. }
  44475. }
  44476. };
  44477. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  44478. var current = this.checkInputs;
  44479. return function () {
  44480. current();
  44481. fn();
  44482. };
  44483. };
  44484. CameraInputsManager.prototype.attachInput = function (input) {
  44485. if (this.attachedElement) {
  44486. input.attachControl(this.attachedElement, this.noPreventDefault);
  44487. }
  44488. };
  44489. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  44490. if (noPreventDefault === void 0) { noPreventDefault = false; }
  44491. if (this.attachedElement) {
  44492. return;
  44493. }
  44494. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44495. this.attachedElement = element;
  44496. this.noPreventDefault = noPreventDefault;
  44497. for (var cam in this.attached) {
  44498. this.attached[cam].attachControl(element, noPreventDefault);
  44499. }
  44500. };
  44501. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  44502. if (disconnect === void 0) { disconnect = false; }
  44503. if (this.attachedElement !== element) {
  44504. return;
  44505. }
  44506. for (var cam in this.attached) {
  44507. this.attached[cam].detachControl(element);
  44508. if (disconnect) {
  44509. this.attached[cam].camera = null;
  44510. }
  44511. }
  44512. this.attachedElement = null;
  44513. };
  44514. CameraInputsManager.prototype.rebuildInputCheck = function () {
  44515. this.checkInputs = function () { };
  44516. for (var cam in this.attached) {
  44517. var input = this.attached[cam];
  44518. if (input.checkInputs) {
  44519. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  44520. }
  44521. }
  44522. };
  44523. /**
  44524. * Remove all attached input methods from a camera
  44525. */
  44526. CameraInputsManager.prototype.clear = function () {
  44527. if (this.attachedElement) {
  44528. this.detachElement(this.attachedElement, true);
  44529. }
  44530. this.attached = {};
  44531. this.attachedElement = null;
  44532. this.checkInputs = function () { };
  44533. };
  44534. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  44535. var inputs = {};
  44536. for (var cam in this.attached) {
  44537. var input = this.attached[cam];
  44538. var res = BABYLON.SerializationHelper.Serialize(input);
  44539. inputs[input.getClassName()] = res;
  44540. }
  44541. serializedCamera.inputsmgr = inputs;
  44542. };
  44543. CameraInputsManager.prototype.parse = function (parsedCamera) {
  44544. var parsedInputs = parsedCamera.inputsmgr;
  44545. if (parsedInputs) {
  44546. this.clear();
  44547. for (var n in parsedInputs) {
  44548. var construct = BABYLON.CameraInputTypes[n];
  44549. if (construct) {
  44550. var parsedinput = parsedInputs[n];
  44551. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  44552. this.add(input);
  44553. }
  44554. }
  44555. }
  44556. else {
  44557. //2016-03-08 this part is for managing backward compatibility
  44558. for (var n in this.attached) {
  44559. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  44560. if (construct) {
  44561. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  44562. this.remove(this.attached[n]);
  44563. this.add(input);
  44564. }
  44565. }
  44566. }
  44567. };
  44568. return CameraInputsManager;
  44569. }());
  44570. BABYLON.CameraInputsManager = CameraInputsManager;
  44571. })(BABYLON || (BABYLON = {}));
  44572. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  44573. "use strict";
  44574. var BABYLON;
  44575. (function (BABYLON) {
  44576. var TargetCamera = /** @class */ (function (_super) {
  44577. __extends(TargetCamera, _super);
  44578. function TargetCamera(name, position, scene) {
  44579. var _this = _super.call(this, name, position, scene) || this;
  44580. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44581. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  44582. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  44583. _this.speed = 2.0;
  44584. _this.noRotationConstraint = false;
  44585. _this.lockedTarget = null;
  44586. _this._currentTarget = BABYLON.Vector3.Zero();
  44587. _this._viewMatrix = BABYLON.Matrix.Zero();
  44588. _this._camMatrix = BABYLON.Matrix.Zero();
  44589. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  44590. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  44591. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  44592. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  44593. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  44594. _this._lookAtTemp = BABYLON.Matrix.Zero();
  44595. _this._tempMatrix = BABYLON.Matrix.Zero();
  44596. return _this;
  44597. }
  44598. TargetCamera.prototype.getFrontPosition = function (distance) {
  44599. this.getWorldMatrix();
  44600. var direction = this.getTarget().subtract(this.position);
  44601. direction.normalize();
  44602. direction.scaleInPlace(distance);
  44603. return this.globalPosition.add(direction);
  44604. };
  44605. TargetCamera.prototype._getLockedTargetPosition = function () {
  44606. if (!this.lockedTarget) {
  44607. return null;
  44608. }
  44609. if (this.lockedTarget.absolutePosition) {
  44610. this.lockedTarget.computeWorldMatrix();
  44611. }
  44612. return this.lockedTarget.absolutePosition || this.lockedTarget;
  44613. };
  44614. TargetCamera.prototype.storeState = function () {
  44615. this._storedPosition = this.position.clone();
  44616. this._storedRotation = this.rotation.clone();
  44617. if (this.rotationQuaternion) {
  44618. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  44619. }
  44620. return _super.prototype.storeState.call(this);
  44621. };
  44622. /**
  44623. * Restored camera state. You must call storeState() first
  44624. */
  44625. TargetCamera.prototype._restoreStateValues = function () {
  44626. if (!_super.prototype._restoreStateValues.call(this)) {
  44627. return false;
  44628. }
  44629. this.position = this._storedPosition.clone();
  44630. this.rotation = this._storedRotation.clone();
  44631. if (this.rotationQuaternion) {
  44632. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  44633. }
  44634. this.cameraDirection.copyFromFloats(0, 0, 0);
  44635. this.cameraRotation.copyFromFloats(0, 0);
  44636. return true;
  44637. };
  44638. // Cache
  44639. TargetCamera.prototype._initCache = function () {
  44640. _super.prototype._initCache.call(this);
  44641. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44642. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44643. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44644. };
  44645. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  44646. if (!ignoreParentClass) {
  44647. _super.prototype._updateCache.call(this);
  44648. }
  44649. var lockedTargetPosition = this._getLockedTargetPosition();
  44650. if (!lockedTargetPosition) {
  44651. this._cache.lockedTarget = null;
  44652. }
  44653. else {
  44654. if (!this._cache.lockedTarget) {
  44655. this._cache.lockedTarget = lockedTargetPosition.clone();
  44656. }
  44657. else {
  44658. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  44659. }
  44660. }
  44661. this._cache.rotation.copyFrom(this.rotation);
  44662. if (this.rotationQuaternion)
  44663. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  44664. };
  44665. // Synchronized
  44666. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  44667. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  44668. return false;
  44669. }
  44670. var lockedTargetPosition = this._getLockedTargetPosition();
  44671. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  44672. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  44673. };
  44674. // Methods
  44675. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  44676. var engine = this.getEngine();
  44677. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  44678. };
  44679. // Target
  44680. TargetCamera.prototype.setTarget = function (target) {
  44681. this.upVector.normalize();
  44682. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  44683. this._camMatrix.invert();
  44684. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  44685. var vDir = target.subtract(this.position);
  44686. if (vDir.x >= 0.0) {
  44687. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  44688. }
  44689. else {
  44690. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  44691. }
  44692. this.rotation.z = 0;
  44693. if (isNaN(this.rotation.x)) {
  44694. this.rotation.x = 0;
  44695. }
  44696. if (isNaN(this.rotation.y)) {
  44697. this.rotation.y = 0;
  44698. }
  44699. if (isNaN(this.rotation.z)) {
  44700. this.rotation.z = 0;
  44701. }
  44702. if (this.rotationQuaternion) {
  44703. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  44704. }
  44705. };
  44706. /**
  44707. * Return the current target position of the camera. This value is expressed in local space.
  44708. */
  44709. TargetCamera.prototype.getTarget = function () {
  44710. return this._currentTarget;
  44711. };
  44712. TargetCamera.prototype._decideIfNeedsToMove = function () {
  44713. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44714. };
  44715. TargetCamera.prototype._updatePosition = function () {
  44716. if (this.parent) {
  44717. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  44718. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  44719. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  44720. return;
  44721. }
  44722. this.position.addInPlace(this.cameraDirection);
  44723. };
  44724. TargetCamera.prototype._checkInputs = function () {
  44725. var needToMove = this._decideIfNeedsToMove();
  44726. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  44727. // Move
  44728. if (needToMove) {
  44729. this._updatePosition();
  44730. }
  44731. // Rotate
  44732. if (needToRotate) {
  44733. this.rotation.x += this.cameraRotation.x;
  44734. this.rotation.y += this.cameraRotation.y;
  44735. //rotate, if quaternion is set and rotation was used
  44736. if (this.rotationQuaternion) {
  44737. var len = this.rotation.lengthSquared();
  44738. if (len) {
  44739. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  44740. }
  44741. }
  44742. if (!this.noRotationConstraint) {
  44743. var limit = (Math.PI / 2) * 0.95;
  44744. if (this.rotation.x > limit)
  44745. this.rotation.x = limit;
  44746. if (this.rotation.x < -limit)
  44747. this.rotation.x = -limit;
  44748. }
  44749. }
  44750. // Inertia
  44751. if (needToMove) {
  44752. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  44753. this.cameraDirection.x = 0;
  44754. }
  44755. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  44756. this.cameraDirection.y = 0;
  44757. }
  44758. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  44759. this.cameraDirection.z = 0;
  44760. }
  44761. this.cameraDirection.scaleInPlace(this.inertia);
  44762. }
  44763. if (needToRotate) {
  44764. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  44765. this.cameraRotation.x = 0;
  44766. }
  44767. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  44768. this.cameraRotation.y = 0;
  44769. }
  44770. this.cameraRotation.scaleInPlace(this.inertia);
  44771. }
  44772. _super.prototype._checkInputs.call(this);
  44773. };
  44774. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  44775. if (this.rotationQuaternion) {
  44776. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  44777. }
  44778. else {
  44779. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  44780. }
  44781. //update the up vector!
  44782. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  44783. };
  44784. TargetCamera.prototype._getViewMatrix = function () {
  44785. if (this.lockedTarget) {
  44786. this.setTarget(this._getLockedTargetPosition());
  44787. }
  44788. // Compute
  44789. this._updateCameraRotationMatrix();
  44790. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  44791. // Computing target and final matrix
  44792. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  44793. if (this.getScene().useRightHandedSystem) {
  44794. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  44795. }
  44796. else {
  44797. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  44798. }
  44799. return this._viewMatrix;
  44800. };
  44801. /**
  44802. * @override
  44803. * Override Camera.createRigCamera
  44804. */
  44805. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44806. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  44807. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  44808. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  44809. if (!this.rotationQuaternion) {
  44810. this.rotationQuaternion = new BABYLON.Quaternion();
  44811. }
  44812. rigCamera._cameraRigParams = {};
  44813. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  44814. }
  44815. return rigCamera;
  44816. }
  44817. return null;
  44818. };
  44819. /**
  44820. * @override
  44821. * Override Camera._updateRigCameras
  44822. */
  44823. TargetCamera.prototype._updateRigCameras = function () {
  44824. var camLeft = this._rigCameras[0];
  44825. var camRight = this._rigCameras[1];
  44826. switch (this.cameraRigMode) {
  44827. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44828. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44829. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44830. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44831. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  44832. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  44833. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  44834. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  44835. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  44836. camLeft.setTarget(this.getTarget());
  44837. camRight.setTarget(this.getTarget());
  44838. break;
  44839. case BABYLON.Camera.RIG_MODE_VR:
  44840. if (camLeft.rotationQuaternion) {
  44841. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  44842. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  44843. }
  44844. else {
  44845. camLeft.rotation.copyFrom(this.rotation);
  44846. camRight.rotation.copyFrom(this.rotation);
  44847. }
  44848. camLeft.position.copyFrom(this.position);
  44849. camRight.position.copyFrom(this.position);
  44850. break;
  44851. }
  44852. _super.prototype._updateRigCameras.call(this);
  44853. };
  44854. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  44855. if (!this._rigCamTransformMatrix) {
  44856. this._rigCamTransformMatrix = new BABYLON.Matrix();
  44857. }
  44858. var target = this.getTarget();
  44859. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  44860. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  44861. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  44862. };
  44863. TargetCamera.prototype.getClassName = function () {
  44864. return "TargetCamera";
  44865. };
  44866. __decorate([
  44867. BABYLON.serializeAsVector3()
  44868. ], TargetCamera.prototype, "rotation", void 0);
  44869. __decorate([
  44870. BABYLON.serialize()
  44871. ], TargetCamera.prototype, "speed", void 0);
  44872. __decorate([
  44873. BABYLON.serializeAsMeshReference("lockedTargetId")
  44874. ], TargetCamera.prototype, "lockedTarget", void 0);
  44875. return TargetCamera;
  44876. }(BABYLON.Camera));
  44877. BABYLON.TargetCamera = TargetCamera;
  44878. })(BABYLON || (BABYLON = {}));
  44879. //# sourceMappingURL=babylon.targetCamera.js.map
  44880. "use strict";
  44881. var BABYLON;
  44882. (function (BABYLON) {
  44883. var FreeCameraMouseInput = /** @class */ (function () {
  44884. function FreeCameraMouseInput(touchEnabled) {
  44885. if (touchEnabled === void 0) { touchEnabled = true; }
  44886. this.touchEnabled = touchEnabled;
  44887. this.buttons = [0, 1, 2];
  44888. this.angularSensibility = 2000.0;
  44889. this.previousPosition = null;
  44890. }
  44891. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  44892. var _this = this;
  44893. var engine = this.camera.getEngine();
  44894. if (!this._pointerInput) {
  44895. this._pointerInput = function (p, s) {
  44896. var evt = p.event;
  44897. if (engine.isInVRExclusivePointerMode) {
  44898. return;
  44899. }
  44900. if (!_this.touchEnabled && evt.pointerType === "touch") {
  44901. return;
  44902. }
  44903. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44904. return;
  44905. }
  44906. var srcElement = (evt.srcElement || evt.target);
  44907. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44908. try {
  44909. srcElement.setPointerCapture(evt.pointerId);
  44910. }
  44911. catch (e) {
  44912. //Nothing to do with the error. Execution will continue.
  44913. }
  44914. _this.previousPosition = {
  44915. x: evt.clientX,
  44916. y: evt.clientY
  44917. };
  44918. if (!noPreventDefault) {
  44919. evt.preventDefault();
  44920. element.focus();
  44921. }
  44922. }
  44923. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44924. try {
  44925. srcElement.releasePointerCapture(evt.pointerId);
  44926. }
  44927. catch (e) {
  44928. //Nothing to do with the error.
  44929. }
  44930. _this.previousPosition = null;
  44931. if (!noPreventDefault) {
  44932. evt.preventDefault();
  44933. }
  44934. }
  44935. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44936. if (!_this.previousPosition || engine.isPointerLock) {
  44937. return;
  44938. }
  44939. var offsetX = evt.clientX - _this.previousPosition.x;
  44940. var offsetY = evt.clientY - _this.previousPosition.y;
  44941. if (_this.camera.getScene().useRightHandedSystem) {
  44942. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44943. }
  44944. else {
  44945. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44946. }
  44947. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44948. _this.previousPosition = {
  44949. x: evt.clientX,
  44950. y: evt.clientY
  44951. };
  44952. if (!noPreventDefault) {
  44953. evt.preventDefault();
  44954. }
  44955. }
  44956. };
  44957. }
  44958. this._onMouseMove = function (evt) {
  44959. if (!engine.isPointerLock) {
  44960. return;
  44961. }
  44962. if (engine.isInVRExclusivePointerMode) {
  44963. return;
  44964. }
  44965. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44966. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44967. if (_this.camera.getScene().useRightHandedSystem) {
  44968. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44969. }
  44970. else {
  44971. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44972. }
  44973. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44974. _this.previousPosition = null;
  44975. if (!noPreventDefault) {
  44976. evt.preventDefault();
  44977. }
  44978. };
  44979. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44980. element.addEventListener("mousemove", this._onMouseMove, false);
  44981. };
  44982. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44983. if (this._observer && element) {
  44984. this.camera.getScene().onPointerObservable.remove(this._observer);
  44985. if (this._onMouseMove) {
  44986. element.removeEventListener("mousemove", this._onMouseMove);
  44987. }
  44988. this._observer = null;
  44989. this._onMouseMove = null;
  44990. this.previousPosition = null;
  44991. }
  44992. };
  44993. FreeCameraMouseInput.prototype.getClassName = function () {
  44994. return "FreeCameraMouseInput";
  44995. };
  44996. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44997. return "mouse";
  44998. };
  44999. __decorate([
  45000. BABYLON.serialize()
  45001. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  45002. __decorate([
  45003. BABYLON.serialize()
  45004. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  45005. return FreeCameraMouseInput;
  45006. }());
  45007. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  45008. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  45009. })(BABYLON || (BABYLON = {}));
  45010. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  45011. "use strict";
  45012. var BABYLON;
  45013. (function (BABYLON) {
  45014. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  45015. function FreeCameraKeyboardMoveInput() {
  45016. this._keys = new Array();
  45017. this.keysUp = [38];
  45018. this.keysDown = [40];
  45019. this.keysLeft = [37];
  45020. this.keysRight = [39];
  45021. }
  45022. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  45023. var _this = this;
  45024. if (this._onCanvasBlurObserver) {
  45025. return;
  45026. }
  45027. this._scene = this.camera.getScene();
  45028. this._engine = this._scene.getEngine();
  45029. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  45030. _this._keys = [];
  45031. });
  45032. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  45033. var evt = info.event;
  45034. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  45035. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  45036. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  45037. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  45038. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  45039. var index = _this._keys.indexOf(evt.keyCode);
  45040. if (index === -1) {
  45041. _this._keys.push(evt.keyCode);
  45042. }
  45043. if (!noPreventDefault) {
  45044. evt.preventDefault();
  45045. }
  45046. }
  45047. }
  45048. else {
  45049. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  45050. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  45051. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  45052. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  45053. var index = _this._keys.indexOf(evt.keyCode);
  45054. if (index >= 0) {
  45055. _this._keys.splice(index, 1);
  45056. }
  45057. if (!noPreventDefault) {
  45058. evt.preventDefault();
  45059. }
  45060. }
  45061. }
  45062. });
  45063. };
  45064. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  45065. if (this._scene) {
  45066. if (this._onKeyboardObserver) {
  45067. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  45068. }
  45069. if (this._onCanvasBlurObserver) {
  45070. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  45071. }
  45072. this._onKeyboardObserver = null;
  45073. this._onCanvasBlurObserver = null;
  45074. }
  45075. this._keys = [];
  45076. };
  45077. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  45078. if (this._onKeyboardObserver) {
  45079. var camera = this.camera;
  45080. // Keyboard
  45081. for (var index = 0; index < this._keys.length; index++) {
  45082. var keyCode = this._keys[index];
  45083. var speed = camera._computeLocalCameraSpeed();
  45084. if (this.keysLeft.indexOf(keyCode) !== -1) {
  45085. camera._localDirection.copyFromFloats(-speed, 0, 0);
  45086. }
  45087. else if (this.keysUp.indexOf(keyCode) !== -1) {
  45088. camera._localDirection.copyFromFloats(0, 0, speed);
  45089. }
  45090. else if (this.keysRight.indexOf(keyCode) !== -1) {
  45091. camera._localDirection.copyFromFloats(speed, 0, 0);
  45092. }
  45093. else if (this.keysDown.indexOf(keyCode) !== -1) {
  45094. camera._localDirection.copyFromFloats(0, 0, -speed);
  45095. }
  45096. if (camera.getScene().useRightHandedSystem) {
  45097. camera._localDirection.z *= -1;
  45098. }
  45099. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  45100. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  45101. camera.cameraDirection.addInPlace(camera._transformedDirection);
  45102. }
  45103. }
  45104. };
  45105. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  45106. return "FreeCameraKeyboardMoveInput";
  45107. };
  45108. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  45109. this._keys = [];
  45110. };
  45111. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  45112. return "keyboard";
  45113. };
  45114. __decorate([
  45115. BABYLON.serialize()
  45116. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  45117. __decorate([
  45118. BABYLON.serialize()
  45119. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  45120. __decorate([
  45121. BABYLON.serialize()
  45122. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  45123. __decorate([
  45124. BABYLON.serialize()
  45125. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  45126. return FreeCameraKeyboardMoveInput;
  45127. }());
  45128. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  45129. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  45130. })(BABYLON || (BABYLON = {}));
  45131. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  45132. "use strict";
  45133. var BABYLON;
  45134. (function (BABYLON) {
  45135. var FreeCameraInputsManager = /** @class */ (function (_super) {
  45136. __extends(FreeCameraInputsManager, _super);
  45137. function FreeCameraInputsManager(camera) {
  45138. return _super.call(this, camera) || this;
  45139. }
  45140. FreeCameraInputsManager.prototype.addKeyboard = function () {
  45141. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  45142. return this;
  45143. };
  45144. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  45145. if (touchEnabled === void 0) { touchEnabled = true; }
  45146. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  45147. return this;
  45148. };
  45149. FreeCameraInputsManager.prototype.addGamepad = function () {
  45150. this.add(new BABYLON.FreeCameraGamepadInput());
  45151. return this;
  45152. };
  45153. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  45154. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  45155. return this;
  45156. };
  45157. FreeCameraInputsManager.prototype.addTouch = function () {
  45158. this.add(new BABYLON.FreeCameraTouchInput());
  45159. return this;
  45160. };
  45161. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  45162. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  45163. return this;
  45164. };
  45165. return FreeCameraInputsManager;
  45166. }(BABYLON.CameraInputsManager));
  45167. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  45168. })(BABYLON || (BABYLON = {}));
  45169. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  45170. "use strict";
  45171. var BABYLON;
  45172. (function (BABYLON) {
  45173. var FreeCamera = /** @class */ (function (_super) {
  45174. __extends(FreeCamera, _super);
  45175. function FreeCamera(name, position, scene) {
  45176. var _this = _super.call(this, name, position, scene) || this;
  45177. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  45178. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  45179. _this.checkCollisions = false;
  45180. _this.applyGravity = false;
  45181. _this._needMoveForGravity = false;
  45182. _this._oldPosition = BABYLON.Vector3.Zero();
  45183. _this._diffPosition = BABYLON.Vector3.Zero();
  45184. _this._newPosition = BABYLON.Vector3.Zero();
  45185. // Collisions
  45186. _this._collisionMask = -1;
  45187. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45188. if (collidedMesh === void 0) { collidedMesh = null; }
  45189. //TODO move this to the collision coordinator!
  45190. if (_this.getScene().workerCollisions)
  45191. newPosition.multiplyInPlace(_this._collider._radius);
  45192. var updatePosition = function (newPos) {
  45193. _this._newPosition.copyFrom(newPos);
  45194. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  45195. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  45196. _this.position.addInPlace(_this._diffPosition);
  45197. if (_this.onCollide && collidedMesh) {
  45198. _this.onCollide(collidedMesh);
  45199. }
  45200. }
  45201. };
  45202. updatePosition(newPosition);
  45203. };
  45204. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  45205. _this.inputs.addKeyboard().addMouse();
  45206. return _this;
  45207. }
  45208. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  45209. //-- begin properties for backward compatibility for inputs
  45210. /**
  45211. * Gets the input sensibility for a mouse input. (default is 2000.0)
  45212. * Higher values reduce sensitivity.
  45213. */
  45214. get: function () {
  45215. var mouse = this.inputs.attached["mouse"];
  45216. if (mouse)
  45217. return mouse.angularSensibility;
  45218. return 0;
  45219. },
  45220. /**
  45221. * Sets the input sensibility for a mouse input. (default is 2000.0)
  45222. * Higher values reduce sensitivity.
  45223. */
  45224. set: function (value) {
  45225. var mouse = this.inputs.attached["mouse"];
  45226. if (mouse)
  45227. mouse.angularSensibility = value;
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  45233. get: function () {
  45234. var keyboard = this.inputs.attached["keyboard"];
  45235. if (keyboard)
  45236. return keyboard.keysUp;
  45237. return [];
  45238. },
  45239. set: function (value) {
  45240. var keyboard = this.inputs.attached["keyboard"];
  45241. if (keyboard)
  45242. keyboard.keysUp = value;
  45243. },
  45244. enumerable: true,
  45245. configurable: true
  45246. });
  45247. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  45248. get: function () {
  45249. var keyboard = this.inputs.attached["keyboard"];
  45250. if (keyboard)
  45251. return keyboard.keysDown;
  45252. return [];
  45253. },
  45254. set: function (value) {
  45255. var keyboard = this.inputs.attached["keyboard"];
  45256. if (keyboard)
  45257. keyboard.keysDown = value;
  45258. },
  45259. enumerable: true,
  45260. configurable: true
  45261. });
  45262. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  45263. get: function () {
  45264. var keyboard = this.inputs.attached["keyboard"];
  45265. if (keyboard)
  45266. return keyboard.keysLeft;
  45267. return [];
  45268. },
  45269. set: function (value) {
  45270. var keyboard = this.inputs.attached["keyboard"];
  45271. if (keyboard)
  45272. keyboard.keysLeft = value;
  45273. },
  45274. enumerable: true,
  45275. configurable: true
  45276. });
  45277. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  45278. get: function () {
  45279. var keyboard = this.inputs.attached["keyboard"];
  45280. if (keyboard)
  45281. return keyboard.keysRight;
  45282. return [];
  45283. },
  45284. set: function (value) {
  45285. var keyboard = this.inputs.attached["keyboard"];
  45286. if (keyboard)
  45287. keyboard.keysRight = value;
  45288. },
  45289. enumerable: true,
  45290. configurable: true
  45291. });
  45292. // Controls
  45293. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45294. this.inputs.attachElement(element, noPreventDefault);
  45295. };
  45296. FreeCamera.prototype.detachControl = function (element) {
  45297. this.inputs.detachElement(element);
  45298. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45299. this.cameraRotation = new BABYLON.Vector2(0, 0);
  45300. };
  45301. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  45302. get: function () {
  45303. return this._collisionMask;
  45304. },
  45305. set: function (mask) {
  45306. this._collisionMask = !isNaN(mask) ? mask : -1;
  45307. },
  45308. enumerable: true,
  45309. configurable: true
  45310. });
  45311. FreeCamera.prototype._collideWithWorld = function (displacement) {
  45312. var globalPosition;
  45313. if (this.parent) {
  45314. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  45315. }
  45316. else {
  45317. globalPosition = this.position;
  45318. }
  45319. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  45320. this._oldPosition.addInPlace(this.ellipsoidOffset);
  45321. if (!this._collider) {
  45322. this._collider = new BABYLON.Collider();
  45323. }
  45324. this._collider._radius = this.ellipsoid;
  45325. this._collider.collisionMask = this._collisionMask;
  45326. //no need for clone, as long as gravity is not on.
  45327. var actualDisplacement = displacement;
  45328. //add gravity to the direction to prevent the dual-collision checking
  45329. if (this.applyGravity) {
  45330. //this prevents mending with cameraDirection, a global variable of the free camera class.
  45331. actualDisplacement = displacement.add(this.getScene().gravity);
  45332. }
  45333. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45334. };
  45335. FreeCamera.prototype._checkInputs = function () {
  45336. if (!this._localDirection) {
  45337. this._localDirection = BABYLON.Vector3.Zero();
  45338. this._transformedDirection = BABYLON.Vector3.Zero();
  45339. }
  45340. this.inputs.checkInputs();
  45341. _super.prototype._checkInputs.call(this);
  45342. };
  45343. FreeCamera.prototype._decideIfNeedsToMove = function () {
  45344. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45345. };
  45346. FreeCamera.prototype._updatePosition = function () {
  45347. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  45348. this._collideWithWorld(this.cameraDirection);
  45349. }
  45350. else {
  45351. _super.prototype._updatePosition.call(this);
  45352. }
  45353. };
  45354. FreeCamera.prototype.dispose = function () {
  45355. this.inputs.clear();
  45356. _super.prototype.dispose.call(this);
  45357. };
  45358. FreeCamera.prototype.getClassName = function () {
  45359. return "FreeCamera";
  45360. };
  45361. __decorate([
  45362. BABYLON.serializeAsVector3()
  45363. ], FreeCamera.prototype, "ellipsoid", void 0);
  45364. __decorate([
  45365. BABYLON.serializeAsVector3()
  45366. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  45367. __decorate([
  45368. BABYLON.serialize()
  45369. ], FreeCamera.prototype, "checkCollisions", void 0);
  45370. __decorate([
  45371. BABYLON.serialize()
  45372. ], FreeCamera.prototype, "applyGravity", void 0);
  45373. return FreeCamera;
  45374. }(BABYLON.TargetCamera));
  45375. BABYLON.FreeCamera = FreeCamera;
  45376. })(BABYLON || (BABYLON = {}));
  45377. //# sourceMappingURL=babylon.freeCamera.js.map
  45378. "use strict";
  45379. var BABYLON;
  45380. (function (BABYLON) {
  45381. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  45382. function ArcRotateCameraKeyboardMoveInput() {
  45383. this._keys = new Array();
  45384. this.keysUp = [38];
  45385. this.keysDown = [40];
  45386. this.keysLeft = [37];
  45387. this.keysRight = [39];
  45388. this.keysReset = [220];
  45389. this.panningSensibility = 50.0;
  45390. this.zoomingSensibility = 25.0;
  45391. this.useAltToZoom = true;
  45392. }
  45393. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  45394. var _this = this;
  45395. if (this._onCanvasBlurObserver) {
  45396. return;
  45397. }
  45398. this._scene = this.camera.getScene();
  45399. this._engine = this._scene.getEngine();
  45400. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  45401. _this._keys = [];
  45402. });
  45403. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  45404. var evt = info.event;
  45405. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  45406. _this._ctrlPressed = evt.ctrlKey;
  45407. _this._altPressed = evt.altKey;
  45408. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  45409. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  45410. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  45411. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  45412. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  45413. var index = _this._keys.indexOf(evt.keyCode);
  45414. if (index === -1) {
  45415. _this._keys.push(evt.keyCode);
  45416. }
  45417. if (evt.preventDefault) {
  45418. if (!noPreventDefault) {
  45419. evt.preventDefault();
  45420. }
  45421. }
  45422. }
  45423. }
  45424. else {
  45425. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  45426. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  45427. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  45428. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  45429. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  45430. var index = _this._keys.indexOf(evt.keyCode);
  45431. if (index >= 0) {
  45432. _this._keys.splice(index, 1);
  45433. }
  45434. if (evt.preventDefault) {
  45435. if (!noPreventDefault) {
  45436. evt.preventDefault();
  45437. }
  45438. }
  45439. }
  45440. }
  45441. });
  45442. };
  45443. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  45444. if (this._scene) {
  45445. if (this._onKeyboardObserver) {
  45446. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  45447. }
  45448. if (this._onCanvasBlurObserver) {
  45449. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  45450. }
  45451. this._onKeyboardObserver = null;
  45452. this._onCanvasBlurObserver = null;
  45453. }
  45454. this._keys = [];
  45455. };
  45456. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  45457. if (this._onKeyboardObserver) {
  45458. var camera = this.camera;
  45459. for (var index = 0; index < this._keys.length; index++) {
  45460. var keyCode = this._keys[index];
  45461. if (this.keysLeft.indexOf(keyCode) !== -1) {
  45462. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  45463. camera.inertialPanningX -= 1 / this.panningSensibility;
  45464. }
  45465. else {
  45466. camera.inertialAlphaOffset -= 0.01;
  45467. }
  45468. }
  45469. else if (this.keysUp.indexOf(keyCode) !== -1) {
  45470. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  45471. camera.inertialPanningY += 1 / this.panningSensibility;
  45472. }
  45473. else if (this._altPressed && this.useAltToZoom) {
  45474. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  45475. }
  45476. else {
  45477. camera.inertialBetaOffset -= 0.01;
  45478. }
  45479. }
  45480. else if (this.keysRight.indexOf(keyCode) !== -1) {
  45481. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  45482. camera.inertialPanningX += 1 / this.panningSensibility;
  45483. }
  45484. else {
  45485. camera.inertialAlphaOffset += 0.01;
  45486. }
  45487. }
  45488. else if (this.keysDown.indexOf(keyCode) !== -1) {
  45489. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  45490. camera.inertialPanningY -= 1 / this.panningSensibility;
  45491. }
  45492. else if (this._altPressed && this.useAltToZoom) {
  45493. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  45494. }
  45495. else {
  45496. camera.inertialBetaOffset += 0.01;
  45497. }
  45498. }
  45499. else if (this.keysReset.indexOf(keyCode) !== -1) {
  45500. camera.restoreState();
  45501. }
  45502. }
  45503. }
  45504. };
  45505. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  45506. return "ArcRotateCameraKeyboardMoveInput";
  45507. };
  45508. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  45509. return "keyboard";
  45510. };
  45511. __decorate([
  45512. BABYLON.serialize()
  45513. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  45514. __decorate([
  45515. BABYLON.serialize()
  45516. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  45517. __decorate([
  45518. BABYLON.serialize()
  45519. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  45520. __decorate([
  45521. BABYLON.serialize()
  45522. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  45523. __decorate([
  45524. BABYLON.serialize()
  45525. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  45526. __decorate([
  45527. BABYLON.serialize()
  45528. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  45529. __decorate([
  45530. BABYLON.serialize()
  45531. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  45532. __decorate([
  45533. BABYLON.serialize()
  45534. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  45535. return ArcRotateCameraKeyboardMoveInput;
  45536. }());
  45537. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  45538. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  45539. })(BABYLON || (BABYLON = {}));
  45540. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  45541. "use strict";
  45542. var BABYLON;
  45543. (function (BABYLON) {
  45544. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  45545. function ArcRotateCameraMouseWheelInput() {
  45546. this.wheelPrecision = 3.0;
  45547. /**
  45548. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  45549. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  45550. */
  45551. this.wheelDeltaPercentage = 0;
  45552. }
  45553. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  45554. var _this = this;
  45555. this._wheel = function (p, s) {
  45556. //sanity check - this should be a PointerWheel event.
  45557. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  45558. return;
  45559. var event = p.event;
  45560. var delta = 0;
  45561. if (event.wheelDelta) {
  45562. if (_this.wheelDeltaPercentage) {
  45563. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  45564. if (event.wheelDelta > 0) {
  45565. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  45566. }
  45567. else {
  45568. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  45569. }
  45570. }
  45571. else {
  45572. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  45573. }
  45574. }
  45575. else if (event.detail) {
  45576. delta = -event.detail / _this.wheelPrecision;
  45577. }
  45578. if (delta)
  45579. _this.camera.inertialRadiusOffset += delta;
  45580. if (event.preventDefault) {
  45581. if (!noPreventDefault) {
  45582. event.preventDefault();
  45583. }
  45584. }
  45585. };
  45586. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  45587. };
  45588. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  45589. if (this._observer && element) {
  45590. this.camera.getScene().onPointerObservable.remove(this._observer);
  45591. this._observer = null;
  45592. this._wheel = null;
  45593. }
  45594. };
  45595. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  45596. return "ArcRotateCameraMouseWheelInput";
  45597. };
  45598. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  45599. return "mousewheel";
  45600. };
  45601. __decorate([
  45602. BABYLON.serialize()
  45603. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  45604. __decorate([
  45605. BABYLON.serialize()
  45606. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  45607. return ArcRotateCameraMouseWheelInput;
  45608. }());
  45609. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  45610. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  45611. })(BABYLON || (BABYLON = {}));
  45612. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  45613. "use strict";
  45614. var BABYLON;
  45615. (function (BABYLON) {
  45616. var ArcRotateCameraPointersInput = /** @class */ (function () {
  45617. function ArcRotateCameraPointersInput() {
  45618. this.buttons = [0, 1, 2];
  45619. this.angularSensibilityX = 1000.0;
  45620. this.angularSensibilityY = 1000.0;
  45621. this.pinchPrecision = 12.0;
  45622. /**
  45623. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  45624. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  45625. */
  45626. this.pinchDeltaPercentage = 0;
  45627. this.panningSensibility = 1000.0;
  45628. this.multiTouchPanning = true;
  45629. this.multiTouchPanAndZoom = true;
  45630. this._isPanClick = false;
  45631. this.pinchInwards = true;
  45632. }
  45633. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  45634. var _this = this;
  45635. var engine = this.camera.getEngine();
  45636. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  45637. var pointA = null;
  45638. var pointB = null;
  45639. var previousPinchSquaredDistance = 0;
  45640. var initialDistance = 0;
  45641. var twoFingerActivityCount = 0;
  45642. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  45643. this._pointerInput = function (p, s) {
  45644. var evt = p.event;
  45645. var isTouch = p.event.pointerType === "touch";
  45646. if (engine.isInVRExclusivePointerMode) {
  45647. return;
  45648. }
  45649. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  45650. return;
  45651. }
  45652. var srcElement = (evt.srcElement || evt.target);
  45653. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  45654. try {
  45655. srcElement.setPointerCapture(evt.pointerId);
  45656. }
  45657. catch (e) {
  45658. //Nothing to do with the error. Execution will continue.
  45659. }
  45660. // Manage panning with pan button click
  45661. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  45662. // manage pointers
  45663. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  45664. if (pointA === null) {
  45665. pointA = cacheSoloPointer;
  45666. }
  45667. else if (pointB === null) {
  45668. pointB = cacheSoloPointer;
  45669. }
  45670. if (!noPreventDefault) {
  45671. evt.preventDefault();
  45672. element.focus();
  45673. }
  45674. }
  45675. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  45676. _this.camera.restoreState();
  45677. }
  45678. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  45679. try {
  45680. srcElement.releasePointerCapture(evt.pointerId);
  45681. }
  45682. catch (e) {
  45683. //Nothing to do with the error.
  45684. }
  45685. cacheSoloPointer = null;
  45686. previousPinchSquaredDistance = 0;
  45687. previousMultiTouchPanPosition.isPaning = false;
  45688. previousMultiTouchPanPosition.isPinching = false;
  45689. twoFingerActivityCount = 0;
  45690. initialDistance = 0;
  45691. if (!isTouch) {
  45692. pointB = null; // Mouse and pen are mono pointer
  45693. }
  45694. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  45695. //but emptying completly pointers collection is required to fix a bug on iPhone :
  45696. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  45697. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  45698. if (engine.badOS) {
  45699. pointA = pointB = null;
  45700. }
  45701. else {
  45702. //only remove the impacted pointer in case of multitouch allowing on most
  45703. //platforms switching from rotate to zoom and pan seamlessly.
  45704. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  45705. pointA = pointB;
  45706. pointB = null;
  45707. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  45708. }
  45709. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  45710. pointB = null;
  45711. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  45712. }
  45713. else {
  45714. pointA = pointB = null;
  45715. }
  45716. }
  45717. if (!noPreventDefault) {
  45718. evt.preventDefault();
  45719. }
  45720. }
  45721. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45722. if (!noPreventDefault) {
  45723. evt.preventDefault();
  45724. }
  45725. // One button down
  45726. if (pointA && pointB === null && cacheSoloPointer) {
  45727. if (_this.panningSensibility !== 0 &&
  45728. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  45729. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  45730. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  45731. }
  45732. else {
  45733. var offsetX = evt.clientX - cacheSoloPointer.x;
  45734. var offsetY = evt.clientY - cacheSoloPointer.y;
  45735. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  45736. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  45737. }
  45738. cacheSoloPointer.x = evt.clientX;
  45739. cacheSoloPointer.y = evt.clientY;
  45740. }
  45741. else if (pointA && pointB) {
  45742. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  45743. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  45744. ed.x = evt.clientX;
  45745. ed.y = evt.clientY;
  45746. var direction = _this.pinchInwards ? 1 : -1;
  45747. var distX = pointA.x - pointB.x;
  45748. var distY = pointA.y - pointB.y;
  45749. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  45750. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  45751. if (previousPinchSquaredDistance === 0) {
  45752. initialDistance = pinchDistance;
  45753. previousPinchSquaredDistance = pinchSquaredDistance;
  45754. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  45755. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  45756. return;
  45757. }
  45758. if (_this.multiTouchPanAndZoom) {
  45759. if (_this.pinchDeltaPercentage) {
  45760. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  45761. }
  45762. else {
  45763. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  45764. (_this.pinchPrecision *
  45765. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  45766. direction);
  45767. }
  45768. if (_this.panningSensibility !== 0) {
  45769. var pointersCenterX = (pointA.x + pointB.x) / 2;
  45770. var pointersCenterY = (pointA.y + pointB.y) / 2;
  45771. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  45772. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  45773. previousMultiTouchPanPosition.x = pointersCenterX;
  45774. previousMultiTouchPanPosition.y = pointersCenterY;
  45775. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  45776. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  45777. }
  45778. }
  45779. else {
  45780. twoFingerActivityCount++;
  45781. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  45782. if (_this.pinchDeltaPercentage) {
  45783. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  45784. }
  45785. else {
  45786. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  45787. (_this.pinchPrecision *
  45788. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  45789. direction);
  45790. }
  45791. previousMultiTouchPanPosition.isPaning = false;
  45792. previousMultiTouchPanPosition.isPinching = true;
  45793. }
  45794. else {
  45795. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  45796. if (!previousMultiTouchPanPosition.isPaning) {
  45797. previousMultiTouchPanPosition.isPaning = true;
  45798. previousMultiTouchPanPosition.isPinching = false;
  45799. previousMultiTouchPanPosition.x = ed.x;
  45800. previousMultiTouchPanPosition.y = ed.y;
  45801. return;
  45802. }
  45803. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  45804. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  45805. }
  45806. }
  45807. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  45808. previousMultiTouchPanPosition.x = ed.x;
  45809. previousMultiTouchPanPosition.y = ed.y;
  45810. }
  45811. }
  45812. previousPinchSquaredDistance = pinchSquaredDistance;
  45813. }
  45814. }
  45815. };
  45816. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  45817. this._onContextMenu = function (evt) {
  45818. evt.preventDefault();
  45819. };
  45820. if (!this.camera._useCtrlForPanning) {
  45821. element.addEventListener("contextmenu", this._onContextMenu, false);
  45822. }
  45823. this._onLostFocus = function () {
  45824. //this._keys = [];
  45825. pointA = pointB = null;
  45826. previousPinchSquaredDistance = 0;
  45827. previousMultiTouchPanPosition.isPaning = false;
  45828. previousMultiTouchPanPosition.isPinching = false;
  45829. twoFingerActivityCount = 0;
  45830. cacheSoloPointer = null;
  45831. initialDistance = 0;
  45832. };
  45833. this._onMouseMove = function (evt) {
  45834. if (!engine.isPointerLock) {
  45835. return;
  45836. }
  45837. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  45838. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  45839. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  45840. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  45841. if (!noPreventDefault) {
  45842. evt.preventDefault();
  45843. }
  45844. };
  45845. this._onGestureStart = function (e) {
  45846. if (window.MSGesture === undefined) {
  45847. return;
  45848. }
  45849. if (!_this._MSGestureHandler) {
  45850. _this._MSGestureHandler = new MSGesture();
  45851. _this._MSGestureHandler.target = element;
  45852. }
  45853. _this._MSGestureHandler.addPointer(e.pointerId);
  45854. };
  45855. this._onGesture = function (e) {
  45856. _this.camera.radius *= e.scale;
  45857. if (e.preventDefault) {
  45858. if (!noPreventDefault) {
  45859. e.stopPropagation();
  45860. e.preventDefault();
  45861. }
  45862. }
  45863. };
  45864. element.addEventListener("mousemove", this._onMouseMove, false);
  45865. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  45866. element.addEventListener("MSGestureChange", this._onGesture, false);
  45867. BABYLON.Tools.RegisterTopRootEvents([
  45868. { name: "blur", handler: this._onLostFocus }
  45869. ]);
  45870. };
  45871. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  45872. if (this._onLostFocus) {
  45873. BABYLON.Tools.UnregisterTopRootEvents([
  45874. { name: "blur", handler: this._onLostFocus }
  45875. ]);
  45876. }
  45877. if (element && this._observer) {
  45878. this.camera.getScene().onPointerObservable.remove(this._observer);
  45879. this._observer = null;
  45880. if (this._onContextMenu) {
  45881. element.removeEventListener("contextmenu", this._onContextMenu);
  45882. }
  45883. if (this._onMouseMove) {
  45884. element.removeEventListener("mousemove", this._onMouseMove);
  45885. }
  45886. if (this._onGestureStart) {
  45887. element.removeEventListener("MSPointerDown", this._onGestureStart);
  45888. }
  45889. if (this._onGesture) {
  45890. element.removeEventListener("MSGestureChange", this._onGesture);
  45891. }
  45892. this._isPanClick = false;
  45893. this.pinchInwards = true;
  45894. this._onMouseMove = null;
  45895. this._onGestureStart = null;
  45896. this._onGesture = null;
  45897. this._MSGestureHandler = null;
  45898. this._onLostFocus = null;
  45899. this._onContextMenu = null;
  45900. }
  45901. };
  45902. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  45903. return "ArcRotateCameraPointersInput";
  45904. };
  45905. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  45906. return "pointers";
  45907. };
  45908. __decorate([
  45909. BABYLON.serialize()
  45910. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  45911. __decorate([
  45912. BABYLON.serialize()
  45913. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  45914. __decorate([
  45915. BABYLON.serialize()
  45916. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  45917. __decorate([
  45918. BABYLON.serialize()
  45919. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  45920. __decorate([
  45921. BABYLON.serialize()
  45922. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  45923. __decorate([
  45924. BABYLON.serialize()
  45925. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  45926. __decorate([
  45927. BABYLON.serialize()
  45928. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  45929. __decorate([
  45930. BABYLON.serialize()
  45931. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  45932. return ArcRotateCameraPointersInput;
  45933. }());
  45934. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  45935. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  45936. })(BABYLON || (BABYLON = {}));
  45937. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  45938. "use strict";
  45939. var BABYLON;
  45940. (function (BABYLON) {
  45941. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  45942. __extends(ArcRotateCameraInputsManager, _super);
  45943. function ArcRotateCameraInputsManager(camera) {
  45944. return _super.call(this, camera) || this;
  45945. }
  45946. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  45947. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  45948. return this;
  45949. };
  45950. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45951. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45952. return this;
  45953. };
  45954. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45955. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45956. return this;
  45957. };
  45958. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45959. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45960. return this;
  45961. };
  45962. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45963. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45964. return this;
  45965. };
  45966. return ArcRotateCameraInputsManager;
  45967. }(BABYLON.CameraInputsManager));
  45968. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45969. })(BABYLON || (BABYLON = {}));
  45970. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45971. "use strict";
  45972. var BABYLON;
  45973. (function (BABYLON) {
  45974. var ArcRotateCamera = /** @class */ (function (_super) {
  45975. __extends(ArcRotateCamera, _super);
  45976. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45977. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45978. _this.inertialAlphaOffset = 0;
  45979. _this.inertialBetaOffset = 0;
  45980. _this.inertialRadiusOffset = 0;
  45981. _this.lowerAlphaLimit = null;
  45982. _this.upperAlphaLimit = null;
  45983. _this.lowerBetaLimit = 0.01;
  45984. _this.upperBetaLimit = Math.PI;
  45985. _this.lowerRadiusLimit = null;
  45986. _this.upperRadiusLimit = null;
  45987. _this.inertialPanningX = 0;
  45988. _this.inertialPanningY = 0;
  45989. _this.pinchToPanMaxDistance = 20;
  45990. _this.panningDistanceLimit = null;
  45991. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45992. _this.panningInertia = 0.9;
  45993. //-- end properties for backward compatibility for inputs
  45994. _this.zoomOnFactor = 1;
  45995. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45996. _this.allowUpsideDown = true;
  45997. _this._viewMatrix = new BABYLON.Matrix();
  45998. // Panning
  45999. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  46000. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  46001. _this.checkCollisions = false;
  46002. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46003. _this._previousPosition = BABYLON.Vector3.Zero();
  46004. _this._collisionVelocity = BABYLON.Vector3.Zero();
  46005. _this._newPosition = BABYLON.Vector3.Zero();
  46006. _this._computationVector = BABYLON.Vector3.Zero();
  46007. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46008. if (collidedMesh === void 0) { collidedMesh = null; }
  46009. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  46010. newPosition.multiplyInPlace(_this._collider._radius);
  46011. }
  46012. if (!collidedMesh) {
  46013. _this._previousPosition.copyFrom(_this.position);
  46014. }
  46015. else {
  46016. _this.setPosition(newPosition);
  46017. if (_this.onCollide) {
  46018. _this.onCollide(collidedMesh);
  46019. }
  46020. }
  46021. // Recompute because of constraints
  46022. var cosa = Math.cos(_this.alpha);
  46023. var sina = Math.sin(_this.alpha);
  46024. var cosb = Math.cos(_this.beta);
  46025. var sinb = Math.sin(_this.beta);
  46026. if (sinb === 0) {
  46027. sinb = 0.0001;
  46028. }
  46029. var target = _this._getTargetPosition();
  46030. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  46031. target.addToRef(_this._computationVector, _this._newPosition);
  46032. _this.position.copyFrom(_this._newPosition);
  46033. var up = _this.upVector;
  46034. if (_this.allowUpsideDown && _this.beta < 0) {
  46035. up = up.clone();
  46036. up = up.negate();
  46037. }
  46038. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  46039. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  46040. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  46041. _this._collisionTriggered = false;
  46042. };
  46043. _this._target = BABYLON.Vector3.Zero();
  46044. if (target) {
  46045. _this.setTarget(target);
  46046. }
  46047. _this.alpha = alpha;
  46048. _this.beta = beta;
  46049. _this.radius = radius;
  46050. _this.getViewMatrix();
  46051. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  46052. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  46053. return _this;
  46054. }
  46055. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  46056. get: function () {
  46057. return this._target;
  46058. },
  46059. set: function (value) {
  46060. this.setTarget(value);
  46061. },
  46062. enumerable: true,
  46063. configurable: true
  46064. });
  46065. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  46066. //-- begin properties for backward compatibility for inputs
  46067. get: function () {
  46068. var pointers = this.inputs.attached["pointers"];
  46069. if (pointers)
  46070. return pointers.angularSensibilityX;
  46071. return 0;
  46072. },
  46073. set: function (value) {
  46074. var pointers = this.inputs.attached["pointers"];
  46075. if (pointers) {
  46076. pointers.angularSensibilityX = value;
  46077. }
  46078. },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  46083. get: function () {
  46084. var pointers = this.inputs.attached["pointers"];
  46085. if (pointers)
  46086. return pointers.angularSensibilityY;
  46087. return 0;
  46088. },
  46089. set: function (value) {
  46090. var pointers = this.inputs.attached["pointers"];
  46091. if (pointers) {
  46092. pointers.angularSensibilityY = value;
  46093. }
  46094. },
  46095. enumerable: true,
  46096. configurable: true
  46097. });
  46098. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  46099. get: function () {
  46100. var pointers = this.inputs.attached["pointers"];
  46101. if (pointers)
  46102. return pointers.pinchPrecision;
  46103. return 0;
  46104. },
  46105. set: function (value) {
  46106. var pointers = this.inputs.attached["pointers"];
  46107. if (pointers) {
  46108. pointers.pinchPrecision = value;
  46109. }
  46110. },
  46111. enumerable: true,
  46112. configurable: true
  46113. });
  46114. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  46115. get: function () {
  46116. var pointers = this.inputs.attached["pointers"];
  46117. if (pointers)
  46118. return pointers.pinchDeltaPercentage;
  46119. return 0;
  46120. },
  46121. set: function (value) {
  46122. var pointers = this.inputs.attached["pointers"];
  46123. if (pointers) {
  46124. pointers.pinchDeltaPercentage = value;
  46125. }
  46126. },
  46127. enumerable: true,
  46128. configurable: true
  46129. });
  46130. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  46131. get: function () {
  46132. var pointers = this.inputs.attached["pointers"];
  46133. if (pointers)
  46134. return pointers.panningSensibility;
  46135. return 0;
  46136. },
  46137. set: function (value) {
  46138. var pointers = this.inputs.attached["pointers"];
  46139. if (pointers) {
  46140. pointers.panningSensibility = value;
  46141. }
  46142. },
  46143. enumerable: true,
  46144. configurable: true
  46145. });
  46146. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  46147. get: function () {
  46148. var keyboard = this.inputs.attached["keyboard"];
  46149. if (keyboard)
  46150. return keyboard.keysUp;
  46151. return [];
  46152. },
  46153. set: function (value) {
  46154. var keyboard = this.inputs.attached["keyboard"];
  46155. if (keyboard)
  46156. keyboard.keysUp = value;
  46157. },
  46158. enumerable: true,
  46159. configurable: true
  46160. });
  46161. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  46162. get: function () {
  46163. var keyboard = this.inputs.attached["keyboard"];
  46164. if (keyboard)
  46165. return keyboard.keysDown;
  46166. return [];
  46167. },
  46168. set: function (value) {
  46169. var keyboard = this.inputs.attached["keyboard"];
  46170. if (keyboard)
  46171. keyboard.keysDown = value;
  46172. },
  46173. enumerable: true,
  46174. configurable: true
  46175. });
  46176. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  46177. get: function () {
  46178. var keyboard = this.inputs.attached["keyboard"];
  46179. if (keyboard)
  46180. return keyboard.keysLeft;
  46181. return [];
  46182. },
  46183. set: function (value) {
  46184. var keyboard = this.inputs.attached["keyboard"];
  46185. if (keyboard)
  46186. keyboard.keysLeft = value;
  46187. },
  46188. enumerable: true,
  46189. configurable: true
  46190. });
  46191. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  46192. get: function () {
  46193. var keyboard = this.inputs.attached["keyboard"];
  46194. if (keyboard)
  46195. return keyboard.keysRight;
  46196. return [];
  46197. },
  46198. set: function (value) {
  46199. var keyboard = this.inputs.attached["keyboard"];
  46200. if (keyboard)
  46201. keyboard.keysRight = value;
  46202. },
  46203. enumerable: true,
  46204. configurable: true
  46205. });
  46206. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  46207. get: function () {
  46208. var mousewheel = this.inputs.attached["mousewheel"];
  46209. if (mousewheel)
  46210. return mousewheel.wheelPrecision;
  46211. return 0;
  46212. },
  46213. set: function (value) {
  46214. var mousewheel = this.inputs.attached["mousewheel"];
  46215. if (mousewheel)
  46216. mousewheel.wheelPrecision = value;
  46217. },
  46218. enumerable: true,
  46219. configurable: true
  46220. });
  46221. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  46222. get: function () {
  46223. var mousewheel = this.inputs.attached["mousewheel"];
  46224. if (mousewheel)
  46225. return mousewheel.wheelDeltaPercentage;
  46226. return 0;
  46227. },
  46228. set: function (value) {
  46229. var mousewheel = this.inputs.attached["mousewheel"];
  46230. if (mousewheel)
  46231. mousewheel.wheelDeltaPercentage = value;
  46232. },
  46233. enumerable: true,
  46234. configurable: true
  46235. });
  46236. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  46237. get: function () {
  46238. return this._bouncingBehavior;
  46239. },
  46240. enumerable: true,
  46241. configurable: true
  46242. });
  46243. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  46244. get: function () {
  46245. return this._bouncingBehavior != null;
  46246. },
  46247. set: function (value) {
  46248. if (value === this.useBouncingBehavior) {
  46249. return;
  46250. }
  46251. if (value) {
  46252. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  46253. this.addBehavior(this._bouncingBehavior);
  46254. }
  46255. else if (this._bouncingBehavior) {
  46256. this.removeBehavior(this._bouncingBehavior);
  46257. this._bouncingBehavior = null;
  46258. }
  46259. },
  46260. enumerable: true,
  46261. configurable: true
  46262. });
  46263. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  46264. get: function () {
  46265. return this._framingBehavior;
  46266. },
  46267. enumerable: true,
  46268. configurable: true
  46269. });
  46270. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  46271. get: function () {
  46272. return this._framingBehavior != null;
  46273. },
  46274. set: function (value) {
  46275. if (value === this.useFramingBehavior) {
  46276. return;
  46277. }
  46278. if (value) {
  46279. this._framingBehavior = new BABYLON.FramingBehavior();
  46280. this.addBehavior(this._framingBehavior);
  46281. }
  46282. else if (this._framingBehavior) {
  46283. this.removeBehavior(this._framingBehavior);
  46284. this._framingBehavior = null;
  46285. }
  46286. },
  46287. enumerable: true,
  46288. configurable: true
  46289. });
  46290. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  46291. get: function () {
  46292. return this._autoRotationBehavior;
  46293. },
  46294. enumerable: true,
  46295. configurable: true
  46296. });
  46297. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  46298. get: function () {
  46299. return this._autoRotationBehavior != null;
  46300. },
  46301. set: function (value) {
  46302. if (value === this.useAutoRotationBehavior) {
  46303. return;
  46304. }
  46305. if (value) {
  46306. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  46307. this.addBehavior(this._autoRotationBehavior);
  46308. }
  46309. else if (this._autoRotationBehavior) {
  46310. this.removeBehavior(this._autoRotationBehavior);
  46311. this._autoRotationBehavior = null;
  46312. }
  46313. },
  46314. enumerable: true,
  46315. configurable: true
  46316. });
  46317. // Cache
  46318. ArcRotateCamera.prototype._initCache = function () {
  46319. _super.prototype._initCache.call(this);
  46320. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46321. this._cache.alpha = undefined;
  46322. this._cache.beta = undefined;
  46323. this._cache.radius = undefined;
  46324. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  46325. };
  46326. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  46327. if (!ignoreParentClass) {
  46328. _super.prototype._updateCache.call(this);
  46329. }
  46330. this._cache._target.copyFrom(this._getTargetPosition());
  46331. this._cache.alpha = this.alpha;
  46332. this._cache.beta = this.beta;
  46333. this._cache.radius = this.radius;
  46334. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  46335. };
  46336. ArcRotateCamera.prototype._getTargetPosition = function () {
  46337. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  46338. var pos = this._targetHost.getAbsolutePosition();
  46339. if (this._targetBoundingCenter) {
  46340. pos.addToRef(this._targetBoundingCenter, this._target);
  46341. }
  46342. else {
  46343. this._target.copyFrom(pos);
  46344. }
  46345. }
  46346. var lockedTargetPosition = this._getLockedTargetPosition();
  46347. if (lockedTargetPosition) {
  46348. return lockedTargetPosition;
  46349. }
  46350. return this._target;
  46351. };
  46352. ArcRotateCamera.prototype.storeState = function () {
  46353. this._storedAlpha = this.alpha;
  46354. this._storedBeta = this.beta;
  46355. this._storedRadius = this.radius;
  46356. this._storedTarget = this._getTargetPosition().clone();
  46357. return _super.prototype.storeState.call(this);
  46358. };
  46359. /**
  46360. * Restored camera state. You must call storeState() first
  46361. */
  46362. ArcRotateCamera.prototype._restoreStateValues = function () {
  46363. if (!_super.prototype._restoreStateValues.call(this)) {
  46364. return false;
  46365. }
  46366. this.alpha = this._storedAlpha;
  46367. this.beta = this._storedBeta;
  46368. this.radius = this._storedRadius;
  46369. this.setTarget(this._storedTarget.clone());
  46370. this.inertialAlphaOffset = 0;
  46371. this.inertialBetaOffset = 0;
  46372. this.inertialRadiusOffset = 0;
  46373. this.inertialPanningX = 0;
  46374. this.inertialPanningY = 0;
  46375. return true;
  46376. };
  46377. // Synchronized
  46378. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  46379. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  46380. return false;
  46381. return this._cache._target.equals(this._getTargetPosition())
  46382. && this._cache.alpha === this.alpha
  46383. && this._cache.beta === this.beta
  46384. && this._cache.radius === this.radius
  46385. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  46386. };
  46387. // Methods
  46388. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  46389. var _this = this;
  46390. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  46391. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  46392. this._useCtrlForPanning = useCtrlForPanning;
  46393. this._panningMouseButton = panningMouseButton;
  46394. this.inputs.attachElement(element, noPreventDefault);
  46395. this._reset = function () {
  46396. _this.inertialAlphaOffset = 0;
  46397. _this.inertialBetaOffset = 0;
  46398. _this.inertialRadiusOffset = 0;
  46399. _this.inertialPanningX = 0;
  46400. _this.inertialPanningY = 0;
  46401. };
  46402. };
  46403. ArcRotateCamera.prototype.detachControl = function (element) {
  46404. this.inputs.detachElement(element);
  46405. if (this._reset) {
  46406. this._reset();
  46407. }
  46408. };
  46409. ArcRotateCamera.prototype._checkInputs = function () {
  46410. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  46411. if (this._collisionTriggered) {
  46412. return;
  46413. }
  46414. this.inputs.checkInputs();
  46415. // Inertia
  46416. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  46417. if (this.getScene().useRightHandedSystem) {
  46418. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  46419. }
  46420. else {
  46421. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  46422. }
  46423. this.beta += this.inertialBetaOffset;
  46424. this.radius -= this.inertialRadiusOffset;
  46425. this.inertialAlphaOffset *= this.inertia;
  46426. this.inertialBetaOffset *= this.inertia;
  46427. this.inertialRadiusOffset *= this.inertia;
  46428. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  46429. this.inertialAlphaOffset = 0;
  46430. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  46431. this.inertialBetaOffset = 0;
  46432. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  46433. this.inertialRadiusOffset = 0;
  46434. }
  46435. // Panning inertia
  46436. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  46437. if (!this._localDirection) {
  46438. this._localDirection = BABYLON.Vector3.Zero();
  46439. this._transformedDirection = BABYLON.Vector3.Zero();
  46440. }
  46441. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  46442. this._localDirection.multiplyInPlace(this.panningAxis);
  46443. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  46444. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  46445. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  46446. if (!this.panningAxis.y) {
  46447. this._transformedDirection.y = 0;
  46448. }
  46449. if (!this._targetHost) {
  46450. if (this.panningDistanceLimit) {
  46451. this._transformedDirection.addInPlace(this._target);
  46452. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  46453. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  46454. this._target.copyFrom(this._transformedDirection);
  46455. }
  46456. }
  46457. else {
  46458. this._target.addInPlace(this._transformedDirection);
  46459. }
  46460. }
  46461. this.inertialPanningX *= this.panningInertia;
  46462. this.inertialPanningY *= this.panningInertia;
  46463. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  46464. this.inertialPanningX = 0;
  46465. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  46466. this.inertialPanningY = 0;
  46467. }
  46468. // Limits
  46469. this._checkLimits();
  46470. _super.prototype._checkInputs.call(this);
  46471. };
  46472. ArcRotateCamera.prototype._checkLimits = function () {
  46473. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  46474. if (this.allowUpsideDown && this.beta > Math.PI) {
  46475. this.beta = this.beta - (2 * Math.PI);
  46476. }
  46477. }
  46478. else {
  46479. if (this.beta < this.lowerBetaLimit) {
  46480. this.beta = this.lowerBetaLimit;
  46481. }
  46482. }
  46483. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  46484. if (this.allowUpsideDown && this.beta < -Math.PI) {
  46485. this.beta = this.beta + (2 * Math.PI);
  46486. }
  46487. }
  46488. else {
  46489. if (this.beta > this.upperBetaLimit) {
  46490. this.beta = this.upperBetaLimit;
  46491. }
  46492. }
  46493. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  46494. this.alpha = this.lowerAlphaLimit;
  46495. }
  46496. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  46497. this.alpha = this.upperAlphaLimit;
  46498. }
  46499. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  46500. this.radius = this.lowerRadiusLimit;
  46501. }
  46502. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  46503. this.radius = this.upperRadiusLimit;
  46504. }
  46505. };
  46506. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  46507. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  46508. this.radius = this._computationVector.length();
  46509. if (this.radius === 0) {
  46510. this.radius = 0.0001; // Just to avoid division by zero
  46511. }
  46512. // Alpha
  46513. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  46514. if (this._computationVector.z < 0) {
  46515. this.alpha = 2 * Math.PI - this.alpha;
  46516. }
  46517. // Beta
  46518. this.beta = Math.acos(this._computationVector.y / this.radius);
  46519. this._checkLimits();
  46520. };
  46521. ArcRotateCamera.prototype.setPosition = function (position) {
  46522. if (this.position.equals(position)) {
  46523. return;
  46524. }
  46525. this.position.copyFrom(position);
  46526. this.rebuildAnglesAndRadius();
  46527. };
  46528. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  46529. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  46530. if (allowSamePosition === void 0) { allowSamePosition = false; }
  46531. if (target.getBoundingInfo) {
  46532. if (toBoundingCenter) {
  46533. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  46534. }
  46535. else {
  46536. this._targetBoundingCenter = null;
  46537. }
  46538. this._targetHost = target;
  46539. this._target = this._getTargetPosition();
  46540. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  46541. }
  46542. else {
  46543. var newTarget = target;
  46544. var currentTarget = this._getTargetPosition();
  46545. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  46546. return;
  46547. }
  46548. this._targetHost = null;
  46549. this._target = newTarget;
  46550. this._targetBoundingCenter = null;
  46551. this.onMeshTargetChangedObservable.notifyObservers(null);
  46552. }
  46553. this.rebuildAnglesAndRadius();
  46554. };
  46555. ArcRotateCamera.prototype._getViewMatrix = function () {
  46556. // Compute
  46557. var cosa = Math.cos(this.alpha);
  46558. var sina = Math.sin(this.alpha);
  46559. var cosb = Math.cos(this.beta);
  46560. var sinb = Math.sin(this.beta);
  46561. if (sinb === 0) {
  46562. sinb = 0.0001;
  46563. }
  46564. var target = this._getTargetPosition();
  46565. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  46566. target.addToRef(this._computationVector, this._newPosition);
  46567. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  46568. if (!this._collider) {
  46569. this._collider = new BABYLON.Collider();
  46570. }
  46571. this._collider._radius = this.collisionRadius;
  46572. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  46573. this._collisionTriggered = true;
  46574. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46575. }
  46576. else {
  46577. this.position.copyFrom(this._newPosition);
  46578. var up = this.upVector;
  46579. if (this.allowUpsideDown && sinb < 0) {
  46580. up = up.clone();
  46581. up = up.negate();
  46582. }
  46583. if (this.getScene().useRightHandedSystem) {
  46584. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  46585. }
  46586. else {
  46587. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  46588. }
  46589. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  46590. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  46591. }
  46592. this._currentTarget = target;
  46593. return this._viewMatrix;
  46594. };
  46595. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  46596. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  46597. meshes = meshes || this.getScene().meshes;
  46598. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  46599. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  46600. this.radius = distance * this.zoomOnFactor;
  46601. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  46602. };
  46603. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  46604. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  46605. var meshesOrMinMaxVector;
  46606. var distance;
  46607. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  46608. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  46609. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  46610. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  46611. }
  46612. else {
  46613. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  46614. meshesOrMinMaxVector = minMaxVectorAndDistance;
  46615. distance = minMaxVectorAndDistance.distance;
  46616. }
  46617. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  46618. if (!doNotUpdateMaxZ) {
  46619. this.maxZ = distance * 2;
  46620. }
  46621. };
  46622. /**
  46623. * @override
  46624. * Override Camera.createRigCamera
  46625. */
  46626. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46627. var alphaShift = 0;
  46628. switch (this.cameraRigMode) {
  46629. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46630. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46631. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46632. case BABYLON.Camera.RIG_MODE_VR:
  46633. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  46634. break;
  46635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46636. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  46637. break;
  46638. }
  46639. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  46640. rigCam._cameraRigParams = {};
  46641. return rigCam;
  46642. };
  46643. /**
  46644. * @override
  46645. * Override Camera._updateRigCameras
  46646. */
  46647. ArcRotateCamera.prototype._updateRigCameras = function () {
  46648. var camLeft = this._rigCameras[0];
  46649. var camRight = this._rigCameras[1];
  46650. camLeft.beta = camRight.beta = this.beta;
  46651. camLeft.radius = camRight.radius = this.radius;
  46652. switch (this.cameraRigMode) {
  46653. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46656. case BABYLON.Camera.RIG_MODE_VR:
  46657. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  46658. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  46659. break;
  46660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46661. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  46662. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  46663. break;
  46664. }
  46665. _super.prototype._updateRigCameras.call(this);
  46666. };
  46667. ArcRotateCamera.prototype.dispose = function () {
  46668. this.inputs.clear();
  46669. _super.prototype.dispose.call(this);
  46670. };
  46671. ArcRotateCamera.prototype.getClassName = function () {
  46672. return "ArcRotateCamera";
  46673. };
  46674. __decorate([
  46675. BABYLON.serialize()
  46676. ], ArcRotateCamera.prototype, "alpha", void 0);
  46677. __decorate([
  46678. BABYLON.serialize()
  46679. ], ArcRotateCamera.prototype, "beta", void 0);
  46680. __decorate([
  46681. BABYLON.serialize()
  46682. ], ArcRotateCamera.prototype, "radius", void 0);
  46683. __decorate([
  46684. BABYLON.serializeAsVector3("target")
  46685. ], ArcRotateCamera.prototype, "_target", void 0);
  46686. __decorate([
  46687. BABYLON.serialize()
  46688. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  46689. __decorate([
  46690. BABYLON.serialize()
  46691. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  46692. __decorate([
  46693. BABYLON.serialize()
  46694. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  46695. __decorate([
  46696. BABYLON.serialize()
  46697. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  46698. __decorate([
  46699. BABYLON.serialize()
  46700. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  46701. __decorate([
  46702. BABYLON.serialize()
  46703. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  46704. __decorate([
  46705. BABYLON.serialize()
  46706. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  46707. __decorate([
  46708. BABYLON.serialize()
  46709. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  46710. __decorate([
  46711. BABYLON.serialize()
  46712. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  46713. __decorate([
  46714. BABYLON.serialize()
  46715. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  46716. __decorate([
  46717. BABYLON.serialize()
  46718. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  46719. __decorate([
  46720. BABYLON.serialize()
  46721. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  46722. __decorate([
  46723. BABYLON.serialize()
  46724. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  46725. __decorate([
  46726. BABYLON.serializeAsVector3()
  46727. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  46728. __decorate([
  46729. BABYLON.serialize()
  46730. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  46731. __decorate([
  46732. BABYLON.serialize()
  46733. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  46734. __decorate([
  46735. BABYLON.serialize()
  46736. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  46737. return ArcRotateCamera;
  46738. }(BABYLON.TargetCamera));
  46739. BABYLON.ArcRotateCamera = ArcRotateCamera;
  46740. })(BABYLON || (BABYLON = {}));
  46741. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  46742. "use strict";
  46743. var BABYLON;
  46744. (function (BABYLON) {
  46745. /**
  46746. * The HemisphericLight simulates the ambient environment light,
  46747. * so the passed direction is the light reflection direction, not the incoming direction.
  46748. */
  46749. var HemisphericLight = /** @class */ (function (_super) {
  46750. __extends(HemisphericLight, _super);
  46751. /**
  46752. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  46753. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  46754. * The HemisphericLight can't cast shadows.
  46755. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46756. * @param name The friendly name of the light
  46757. * @param direction The direction of the light reflection
  46758. * @param scene The scene the light belongs to
  46759. */
  46760. function HemisphericLight(name, direction, scene) {
  46761. var _this = _super.call(this, name, scene) || this;
  46762. /**
  46763. * The groundColor is the light in the opposite direction to the one specified during creation.
  46764. * 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.
  46765. */
  46766. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  46767. _this.direction = direction || BABYLON.Vector3.Up();
  46768. return _this;
  46769. }
  46770. HemisphericLight.prototype._buildUniformLayout = function () {
  46771. this._uniformBuffer.addUniform("vLightData", 4);
  46772. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46773. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46774. this._uniformBuffer.addUniform("vLightGround", 3);
  46775. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46776. this._uniformBuffer.addUniform("depthValues", 2);
  46777. this._uniformBuffer.create();
  46778. };
  46779. /**
  46780. * Returns the string "HemisphericLight".
  46781. * @return The class name
  46782. */
  46783. HemisphericLight.prototype.getClassName = function () {
  46784. return "HemisphericLight";
  46785. };
  46786. /**
  46787. * Sets the HemisphericLight direction towards the passed target (Vector3).
  46788. * Returns the updated direction.
  46789. * @param target The target the direction should point to
  46790. * @return The computed direction
  46791. */
  46792. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  46793. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  46794. return this.direction;
  46795. };
  46796. /**
  46797. * Returns the shadow generator associated to the light.
  46798. * @returns Always null for hemispheric lights because it does not support shadows.
  46799. */
  46800. HemisphericLight.prototype.getShadowGenerator = function () {
  46801. return null;
  46802. };
  46803. /**
  46804. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  46805. * @param effect The effect to update
  46806. * @param lightIndex The index of the light in the effect to update
  46807. * @returns The hemispheric light
  46808. */
  46809. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  46810. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46811. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  46812. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  46813. return this;
  46814. };
  46815. /**
  46816. * @ignore internal use only.
  46817. */
  46818. HemisphericLight.prototype._getWorldMatrix = function () {
  46819. if (!this._worldMatrix) {
  46820. this._worldMatrix = BABYLON.Matrix.Identity();
  46821. }
  46822. return this._worldMatrix;
  46823. };
  46824. /**
  46825. * Returns the integer 3.
  46826. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46827. */
  46828. HemisphericLight.prototype.getTypeID = function () {
  46829. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  46830. };
  46831. __decorate([
  46832. BABYLON.serializeAsColor3()
  46833. ], HemisphericLight.prototype, "groundColor", void 0);
  46834. __decorate([
  46835. BABYLON.serializeAsVector3()
  46836. ], HemisphericLight.prototype, "direction", void 0);
  46837. return HemisphericLight;
  46838. }(BABYLON.Light));
  46839. BABYLON.HemisphericLight = HemisphericLight;
  46840. })(BABYLON || (BABYLON = {}));
  46841. //# sourceMappingURL=babylon.hemisphericLight.js.map
  46842. "use strict";
  46843. var BABYLON;
  46844. (function (BABYLON) {
  46845. /**
  46846. * Base implementation IShadowLight
  46847. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  46848. */
  46849. var ShadowLight = /** @class */ (function (_super) {
  46850. __extends(ShadowLight, _super);
  46851. function ShadowLight() {
  46852. var _this = _super !== null && _super.apply(this, arguments) || this;
  46853. _this._needProjectionMatrixCompute = true;
  46854. return _this;
  46855. }
  46856. ShadowLight.prototype._setPosition = function (value) {
  46857. this._position = value;
  46858. };
  46859. Object.defineProperty(ShadowLight.prototype, "position", {
  46860. /**
  46861. * Sets the position the shadow will be casted from. Also use as the light position for both
  46862. * point and spot lights.
  46863. */
  46864. get: function () {
  46865. return this._position;
  46866. },
  46867. /**
  46868. * Sets the position the shadow will be casted from. Also use as the light position for both
  46869. * point and spot lights.
  46870. */
  46871. set: function (value) {
  46872. this._setPosition(value);
  46873. },
  46874. enumerable: true,
  46875. configurable: true
  46876. });
  46877. ShadowLight.prototype._setDirection = function (value) {
  46878. this._direction = value;
  46879. };
  46880. Object.defineProperty(ShadowLight.prototype, "direction", {
  46881. /**
  46882. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  46883. * Also use as the light direction on spot and directional lights.
  46884. */
  46885. get: function () {
  46886. return this._direction;
  46887. },
  46888. /**
  46889. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  46890. * Also use as the light direction on spot and directional lights.
  46891. */
  46892. set: function (value) {
  46893. this._setDirection(value);
  46894. },
  46895. enumerable: true,
  46896. configurable: true
  46897. });
  46898. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  46899. /**
  46900. * Gets the shadow projection clipping minimum z value.
  46901. */
  46902. get: function () {
  46903. return this._shadowMinZ;
  46904. },
  46905. /**
  46906. * Sets the shadow projection clipping minimum z value.
  46907. */
  46908. set: function (value) {
  46909. this._shadowMinZ = value;
  46910. this.forceProjectionMatrixCompute();
  46911. },
  46912. enumerable: true,
  46913. configurable: true
  46914. });
  46915. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  46916. /**
  46917. * Sets the shadow projection clipping maximum z value.
  46918. */
  46919. get: function () {
  46920. return this._shadowMaxZ;
  46921. },
  46922. /**
  46923. * Gets the shadow projection clipping maximum z value.
  46924. */
  46925. set: function (value) {
  46926. this._shadowMaxZ = value;
  46927. this.forceProjectionMatrixCompute();
  46928. },
  46929. enumerable: true,
  46930. configurable: true
  46931. });
  46932. /**
  46933. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  46934. * @returns true if the information has been computed, false if it does not need to (no parenting)
  46935. */
  46936. ShadowLight.prototype.computeTransformedInformation = function () {
  46937. if (this.parent && this.parent.getWorldMatrix) {
  46938. if (!this.transformedPosition) {
  46939. this.transformedPosition = BABYLON.Vector3.Zero();
  46940. }
  46941. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  46942. // In case the direction is present.
  46943. if (this.direction) {
  46944. if (!this.transformedDirection) {
  46945. this.transformedDirection = BABYLON.Vector3.Zero();
  46946. }
  46947. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  46948. }
  46949. return true;
  46950. }
  46951. return false;
  46952. };
  46953. /**
  46954. * Return the depth scale used for the shadow map.
  46955. * @returns the depth scale.
  46956. */
  46957. ShadowLight.prototype.getDepthScale = function () {
  46958. return 50.0;
  46959. };
  46960. /**
  46961. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46962. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46963. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46964. */
  46965. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46966. return this.transformedDirection ? this.transformedDirection : this.direction;
  46967. };
  46968. /**
  46969. * Returns the ShadowLight absolute position in the World.
  46970. * @returns the position vector in world space
  46971. */
  46972. ShadowLight.prototype.getAbsolutePosition = function () {
  46973. return this.transformedPosition ? this.transformedPosition : this.position;
  46974. };
  46975. /**
  46976. * Sets the ShadowLight direction toward the passed target.
  46977. * @param target The point tot target in local space
  46978. * @returns the updated ShadowLight direction
  46979. */
  46980. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46981. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46982. return this.direction;
  46983. };
  46984. /**
  46985. * Returns the light rotation in euler definition.
  46986. * @returns the x y z rotation in local space.
  46987. */
  46988. ShadowLight.prototype.getRotation = function () {
  46989. this.direction.normalize();
  46990. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46991. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46992. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46993. };
  46994. /**
  46995. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46996. * @returns true if a cube texture needs to be use
  46997. */
  46998. ShadowLight.prototype.needCube = function () {
  46999. return false;
  47000. };
  47001. /**
  47002. * Detects if the projection matrix requires to be recomputed this frame.
  47003. * @returns true if it requires to be recomputed otherwise, false.
  47004. */
  47005. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  47006. return this._needProjectionMatrixCompute;
  47007. };
  47008. /**
  47009. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  47010. */
  47011. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  47012. this._needProjectionMatrixCompute = true;
  47013. };
  47014. /**
  47015. * Get the world matrix of the sahdow lights.
  47016. * @ignore Internal Use Only
  47017. */
  47018. ShadowLight.prototype._getWorldMatrix = function () {
  47019. if (!this._worldMatrix) {
  47020. this._worldMatrix = BABYLON.Matrix.Identity();
  47021. }
  47022. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  47023. return this._worldMatrix;
  47024. };
  47025. /**
  47026. * Gets the minZ used for shadow according to both the scene and the light.
  47027. * @param activeCamera The camera we are returning the min for
  47028. * @returns the depth min z
  47029. */
  47030. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  47031. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  47032. };
  47033. /**
  47034. * Gets the maxZ used for shadow according to both the scene and the light.
  47035. * @param activeCamera The camera we are returning the max for
  47036. * @returns the depth max z
  47037. */
  47038. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  47039. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  47040. };
  47041. /**
  47042. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  47043. * @param matrix The materix to updated with the projection information
  47044. * @param viewMatrix The transform matrix of the light
  47045. * @param renderList The list of mesh to render in the map
  47046. * @returns The current light
  47047. */
  47048. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  47049. if (this.customProjectionMatrixBuilder) {
  47050. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  47051. }
  47052. else {
  47053. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  47054. }
  47055. return this;
  47056. };
  47057. __decorate([
  47058. BABYLON.serializeAsVector3()
  47059. ], ShadowLight.prototype, "position", null);
  47060. __decorate([
  47061. BABYLON.serializeAsVector3()
  47062. ], ShadowLight.prototype, "direction", null);
  47063. __decorate([
  47064. BABYLON.serialize()
  47065. ], ShadowLight.prototype, "shadowMinZ", null);
  47066. __decorate([
  47067. BABYLON.serialize()
  47068. ], ShadowLight.prototype, "shadowMaxZ", null);
  47069. return ShadowLight;
  47070. }(BABYLON.Light));
  47071. BABYLON.ShadowLight = ShadowLight;
  47072. })(BABYLON || (BABYLON = {}));
  47073. //# sourceMappingURL=babylon.shadowLight.js.map
  47074. "use strict";
  47075. var BABYLON;
  47076. (function (BABYLON) {
  47077. /**
  47078. * A point light is a light defined by an unique point in world space.
  47079. * The light is emitted in every direction from this point.
  47080. * A good example of a point light is a standard light bulb.
  47081. * Documentation: https://doc.babylonjs.com/babylon101/lights
  47082. */
  47083. var PointLight = /** @class */ (function (_super) {
  47084. __extends(PointLight, _super);
  47085. /**
  47086. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  47087. * A PointLight emits the light in every direction.
  47088. * It can cast shadows.
  47089. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  47090. * ```javascript
  47091. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  47092. * ```
  47093. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47094. * @param name The light friendly name
  47095. * @param position The position of the point light in the scene
  47096. * @param scene The scene the lights belongs to
  47097. */
  47098. function PointLight(name, position, scene) {
  47099. var _this = _super.call(this, name, scene) || this;
  47100. _this._shadowAngle = Math.PI / 2;
  47101. _this.position = position;
  47102. return _this;
  47103. }
  47104. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  47105. /**
  47106. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  47107. * This specifies what angle the shadow will use to be created.
  47108. *
  47109. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  47110. */
  47111. get: function () {
  47112. return this._shadowAngle;
  47113. },
  47114. /**
  47115. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  47116. * This specifies what angle the shadow will use to be created.
  47117. *
  47118. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  47119. */
  47120. set: function (value) {
  47121. this._shadowAngle = value;
  47122. this.forceProjectionMatrixCompute();
  47123. },
  47124. enumerable: true,
  47125. configurable: true
  47126. });
  47127. Object.defineProperty(PointLight.prototype, "direction", {
  47128. /**
  47129. * Gets the direction if it has been set.
  47130. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  47131. */
  47132. get: function () {
  47133. return this._direction;
  47134. },
  47135. /**
  47136. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  47137. */
  47138. set: function (value) {
  47139. var previousNeedCube = this.needCube();
  47140. this._direction = value;
  47141. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  47142. this._shadowGenerator.recreateShadowMap();
  47143. }
  47144. },
  47145. enumerable: true,
  47146. configurable: true
  47147. });
  47148. /**
  47149. * Returns the string "PointLight"
  47150. * @returns the class name
  47151. */
  47152. PointLight.prototype.getClassName = function () {
  47153. return "PointLight";
  47154. };
  47155. /**
  47156. * Returns the integer 0.
  47157. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47158. */
  47159. PointLight.prototype.getTypeID = function () {
  47160. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  47161. };
  47162. /**
  47163. * Specifies wether or not the shadowmap should be a cube texture.
  47164. * @returns true if the shadowmap needs to be a cube texture.
  47165. */
  47166. PointLight.prototype.needCube = function () {
  47167. return !this.direction;
  47168. };
  47169. /**
  47170. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  47171. * @param faceIndex The index of the face we are computed the direction to generate shadow
  47172. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  47173. */
  47174. PointLight.prototype.getShadowDirection = function (faceIndex) {
  47175. if (this.direction) {
  47176. return _super.prototype.getShadowDirection.call(this, faceIndex);
  47177. }
  47178. else {
  47179. switch (faceIndex) {
  47180. case 0:
  47181. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  47182. case 1:
  47183. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  47184. case 2:
  47185. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  47186. case 3:
  47187. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  47188. case 4:
  47189. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  47190. case 5:
  47191. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  47192. }
  47193. }
  47194. return BABYLON.Vector3.Zero();
  47195. };
  47196. /**
  47197. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  47198. * - fov = PI / 2
  47199. * - aspect ratio : 1.0
  47200. * - z-near and far equal to the active camera minZ and maxZ.
  47201. * Returns the PointLight.
  47202. */
  47203. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  47204. var activeCamera = this.getScene().activeCamera;
  47205. if (!activeCamera) {
  47206. return;
  47207. }
  47208. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  47209. };
  47210. PointLight.prototype._buildUniformLayout = function () {
  47211. this._uniformBuffer.addUniform("vLightData", 4);
  47212. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47213. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47214. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47215. this._uniformBuffer.addUniform("depthValues", 2);
  47216. this._uniformBuffer.create();
  47217. };
  47218. /**
  47219. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  47220. * @param effect The effect to update
  47221. * @param lightIndex The index of the light in the effect to update
  47222. * @returns The point light
  47223. */
  47224. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  47225. if (this.computeTransformedInformation()) {
  47226. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  47227. return this;
  47228. }
  47229. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  47230. return this;
  47231. };
  47232. __decorate([
  47233. BABYLON.serialize()
  47234. ], PointLight.prototype, "shadowAngle", null);
  47235. return PointLight;
  47236. }(BABYLON.ShadowLight));
  47237. BABYLON.PointLight = PointLight;
  47238. })(BABYLON || (BABYLON = {}));
  47239. //# sourceMappingURL=babylon.pointLight.js.map
  47240. "use strict";
  47241. var BABYLON;
  47242. (function (BABYLON) {
  47243. /**
  47244. * A directional light is defined by a direction (what a surprise!).
  47245. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  47246. * 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.
  47247. * Documentation: https://doc.babylonjs.com/babylon101/lights
  47248. */
  47249. var DirectionalLight = /** @class */ (function (_super) {
  47250. __extends(DirectionalLight, _super);
  47251. /**
  47252. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  47253. * The directional light is emitted from everywhere in the given direction.
  47254. * It can cast shawdows.
  47255. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47256. * @param name The friendly name of the light
  47257. * @param direction The direction of the light
  47258. * @param scene The scene the light belongs to
  47259. */
  47260. function DirectionalLight(name, direction, scene) {
  47261. var _this = _super.call(this, name, scene) || this;
  47262. _this._shadowFrustumSize = 0;
  47263. _this._shadowOrthoScale = 0.1;
  47264. /**
  47265. * Automatically compute the projection matrix to best fit (including all the casters)
  47266. * on each frame.
  47267. */
  47268. _this.autoUpdateExtends = true;
  47269. // Cache
  47270. _this._orthoLeft = Number.MAX_VALUE;
  47271. _this._orthoRight = Number.MIN_VALUE;
  47272. _this._orthoTop = Number.MIN_VALUE;
  47273. _this._orthoBottom = Number.MAX_VALUE;
  47274. _this.position = direction.scale(-1.0);
  47275. _this.direction = direction;
  47276. return _this;
  47277. }
  47278. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  47279. /**
  47280. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  47281. */
  47282. get: function () {
  47283. return this._shadowFrustumSize;
  47284. },
  47285. /**
  47286. * Specifies a fix frustum size for the shadow generation.
  47287. */
  47288. set: function (value) {
  47289. this._shadowFrustumSize = value;
  47290. this.forceProjectionMatrixCompute();
  47291. },
  47292. enumerable: true,
  47293. configurable: true
  47294. });
  47295. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  47296. /**
  47297. * Gets the shadow projection scale against the optimal computed one.
  47298. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  47299. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  47300. */
  47301. get: function () {
  47302. return this._shadowOrthoScale;
  47303. },
  47304. /**
  47305. * Sets the shadow projection scale against the optimal computed one.
  47306. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  47307. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  47308. */
  47309. set: function (value) {
  47310. this._shadowOrthoScale = value;
  47311. this.forceProjectionMatrixCompute();
  47312. },
  47313. enumerable: true,
  47314. configurable: true
  47315. });
  47316. /**
  47317. * Returns the string "DirectionalLight".
  47318. * @return The class name
  47319. */
  47320. DirectionalLight.prototype.getClassName = function () {
  47321. return "DirectionalLight";
  47322. };
  47323. /**
  47324. * Returns the integer 1.
  47325. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47326. */
  47327. DirectionalLight.prototype.getTypeID = function () {
  47328. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  47329. };
  47330. /**
  47331. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  47332. * Returns the DirectionalLight Shadow projection matrix.
  47333. */
  47334. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  47335. if (this.shadowFrustumSize > 0) {
  47336. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  47337. }
  47338. else {
  47339. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  47340. }
  47341. };
  47342. /**
  47343. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  47344. * Returns the DirectionalLight Shadow projection matrix.
  47345. */
  47346. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  47347. var activeCamera = this.getScene().activeCamera;
  47348. if (!activeCamera) {
  47349. return;
  47350. }
  47351. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  47352. };
  47353. /**
  47354. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  47355. * Returns the DirectionalLight Shadow projection matrix.
  47356. */
  47357. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  47358. var activeCamera = this.getScene().activeCamera;
  47359. if (!activeCamera) {
  47360. return;
  47361. }
  47362. // Check extends
  47363. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  47364. var tempVector3 = BABYLON.Vector3.Zero();
  47365. this._orthoLeft = Number.MAX_VALUE;
  47366. this._orthoRight = Number.MIN_VALUE;
  47367. this._orthoTop = Number.MIN_VALUE;
  47368. this._orthoBottom = Number.MAX_VALUE;
  47369. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  47370. var mesh = renderList[meshIndex];
  47371. if (!mesh) {
  47372. continue;
  47373. }
  47374. var boundingInfo = mesh.getBoundingInfo();
  47375. var boundingBox = boundingInfo.boundingBox;
  47376. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  47377. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  47378. if (tempVector3.x < this._orthoLeft)
  47379. this._orthoLeft = tempVector3.x;
  47380. if (tempVector3.y < this._orthoBottom)
  47381. this._orthoBottom = tempVector3.y;
  47382. if (tempVector3.x > this._orthoRight)
  47383. this._orthoRight = tempVector3.x;
  47384. if (tempVector3.y > this._orthoTop)
  47385. this._orthoTop = tempVector3.y;
  47386. }
  47387. }
  47388. }
  47389. var xOffset = this._orthoRight - this._orthoLeft;
  47390. var yOffset = this._orthoTop - this._orthoBottom;
  47391. 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);
  47392. };
  47393. DirectionalLight.prototype._buildUniformLayout = function () {
  47394. this._uniformBuffer.addUniform("vLightData", 4);
  47395. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47396. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47397. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47398. this._uniformBuffer.addUniform("depthValues", 2);
  47399. this._uniformBuffer.create();
  47400. };
  47401. /**
  47402. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  47403. * @param effect The effect to update
  47404. * @param lightIndex The index of the light in the effect to update
  47405. * @returns The directional light
  47406. */
  47407. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  47408. if (this.computeTransformedInformation()) {
  47409. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  47410. return this;
  47411. }
  47412. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  47413. return this;
  47414. };
  47415. /**
  47416. * Gets the minZ used for shadow according to both the scene and the light.
  47417. *
  47418. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  47419. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  47420. * @param activeCamera The camera we are returning the min for
  47421. * @returns the depth min z
  47422. */
  47423. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  47424. return 1;
  47425. };
  47426. /**
  47427. * Gets the maxZ used for shadow according to both the scene and the light.
  47428. *
  47429. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  47430. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  47431. * @param activeCamera The camera we are returning the max for
  47432. * @returns the depth max z
  47433. */
  47434. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  47435. return 1;
  47436. };
  47437. __decorate([
  47438. BABYLON.serialize()
  47439. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  47440. __decorate([
  47441. BABYLON.serialize()
  47442. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  47443. __decorate([
  47444. BABYLON.serialize()
  47445. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  47446. return DirectionalLight;
  47447. }(BABYLON.ShadowLight));
  47448. BABYLON.DirectionalLight = DirectionalLight;
  47449. })(BABYLON || (BABYLON = {}));
  47450. //# sourceMappingURL=babylon.directionalLight.js.map
  47451. "use strict";
  47452. var BABYLON;
  47453. (function (BABYLON) {
  47454. /**
  47455. * A spot light is defined by a position, a direction, an angle, and an exponent.
  47456. * These values define a cone of light starting from the position, emitting toward the direction.
  47457. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  47458. * and the exponent defines the speed of the decay of the light with distance (reach).
  47459. * Documentation: https://doc.babylonjs.com/babylon101/lights
  47460. */
  47461. var SpotLight = /** @class */ (function (_super) {
  47462. __extends(SpotLight, _super);
  47463. /**
  47464. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  47465. * It can cast shadows.
  47466. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47467. * @param name The light friendly name
  47468. * @param position The position of the spot light in the scene
  47469. * @param direction The direction of the light in the scene
  47470. * @param angle The cone angle of the light in Radians
  47471. * @param exponent The light decay speed with the distance from the emission spot
  47472. * @param scene The scene the lights belongs to
  47473. */
  47474. function SpotLight(name, position, direction, angle, exponent, scene) {
  47475. var _this = _super.call(this, name, scene) || this;
  47476. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  47477. _this._projectionTextureLightNear = 1e-6;
  47478. _this._projectionTextureLightFar = 1000.0;
  47479. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  47480. _this._projectionTextureViewLightDirty = true;
  47481. _this._projectionTextureProjectionLightDirty = true;
  47482. _this._projectionTextureDirty = true;
  47483. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  47484. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  47485. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  47486. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  47487. _this.position = position;
  47488. _this.direction = direction;
  47489. _this.angle = angle;
  47490. _this.exponent = exponent;
  47491. return _this;
  47492. }
  47493. Object.defineProperty(SpotLight.prototype, "angle", {
  47494. /**
  47495. * Gets the cone angle of the spot light in Radians.
  47496. */
  47497. get: function () {
  47498. return this._angle;
  47499. },
  47500. /**
  47501. * Sets the cone angle of the spot light in Radians.
  47502. */
  47503. set: function (value) {
  47504. this._angle = value;
  47505. this._projectionTextureProjectionLightDirty = true;
  47506. this.forceProjectionMatrixCompute();
  47507. },
  47508. enumerable: true,
  47509. configurable: true
  47510. });
  47511. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  47512. /**
  47513. * Allows scaling the angle of the light for shadow generation only.
  47514. */
  47515. get: function () {
  47516. return this._shadowAngleScale;
  47517. },
  47518. /**
  47519. * Allows scaling the angle of the light for shadow generation only.
  47520. */
  47521. set: function (value) {
  47522. this._shadowAngleScale = value;
  47523. this.forceProjectionMatrixCompute();
  47524. },
  47525. enumerable: true,
  47526. configurable: true
  47527. });
  47528. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  47529. /**
  47530. * Allows reading the projecton texture
  47531. */
  47532. get: function () {
  47533. return this._projectionTextureMatrix;
  47534. },
  47535. enumerable: true,
  47536. configurable: true
  47537. });
  47538. ;
  47539. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  47540. /**
  47541. * Gets the near clip of the Spotlight for texture projection.
  47542. */
  47543. get: function () {
  47544. return this._projectionTextureLightNear;
  47545. },
  47546. /**
  47547. * Sets the near clip of the Spotlight for texture projection.
  47548. */
  47549. set: function (value) {
  47550. this._projectionTextureLightNear = value;
  47551. this._projectionTextureProjectionLightDirty = true;
  47552. },
  47553. enumerable: true,
  47554. configurable: true
  47555. });
  47556. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  47557. /**
  47558. * Gets the far clip of the Spotlight for texture projection.
  47559. */
  47560. get: function () {
  47561. return this._projectionTextureLightFar;
  47562. },
  47563. /**
  47564. * Sets the far clip of the Spotlight for texture projection.
  47565. */
  47566. set: function (value) {
  47567. this._projectionTextureLightFar = value;
  47568. this._projectionTextureProjectionLightDirty = true;
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  47574. /**
  47575. * Gets the Up vector of the Spotlight for texture projection.
  47576. */
  47577. get: function () {
  47578. return this._projectionTextureUpDirection;
  47579. },
  47580. /**
  47581. * Sets the Up vector of the Spotlight for texture projection.
  47582. */
  47583. set: function (value) {
  47584. this._projectionTextureUpDirection = value;
  47585. this._projectionTextureProjectionLightDirty = true;
  47586. },
  47587. enumerable: true,
  47588. configurable: true
  47589. });
  47590. ;
  47591. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  47592. /**
  47593. * Gets the projection texture of the light.
  47594. */
  47595. get: function () {
  47596. return this._projectionTexture;
  47597. },
  47598. /**
  47599. * Sets the projection texture of the light.
  47600. */
  47601. set: function (value) {
  47602. this._projectionTexture = value;
  47603. this._projectionTextureDirty = true;
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. /**
  47609. * Returns the string "SpotLight".
  47610. * @returns the class name
  47611. */
  47612. SpotLight.prototype.getClassName = function () {
  47613. return "SpotLight";
  47614. };
  47615. /**
  47616. * Returns the integer 2.
  47617. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47618. */
  47619. SpotLight.prototype.getTypeID = function () {
  47620. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  47621. };
  47622. /**
  47623. * Overrides the direction setter to recompute the projection texture view light Matrix.
  47624. */
  47625. SpotLight.prototype._setDirection = function (value) {
  47626. _super.prototype._setDirection.call(this, value);
  47627. this._projectionTextureViewLightDirty = true;
  47628. };
  47629. /**
  47630. * Overrides the position setter to recompute the projection texture view light Matrix.
  47631. */
  47632. SpotLight.prototype._setPosition = function (value) {
  47633. _super.prototype._setPosition.call(this, value);
  47634. this._projectionTextureViewLightDirty = true;
  47635. };
  47636. /**
  47637. * 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.
  47638. * Returns the SpotLight.
  47639. */
  47640. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  47641. var activeCamera = this.getScene().activeCamera;
  47642. if (!activeCamera) {
  47643. return;
  47644. }
  47645. this._shadowAngleScale = this._shadowAngleScale || 1;
  47646. var angle = this._shadowAngleScale * this._angle;
  47647. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  47648. };
  47649. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  47650. this._projectionTextureViewLightDirty = false;
  47651. this._projectionTextureDirty = true;
  47652. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  47653. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  47654. };
  47655. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  47656. this._projectionTextureProjectionLightDirty = false;
  47657. this._projectionTextureDirty = true;
  47658. var light_far = this.projectionTextureLightFar;
  47659. var light_near = this.projectionTextureLightNear;
  47660. var P = light_far / (light_far - light_near);
  47661. var Q = -P * light_near;
  47662. var S = 1.0 / Math.tan(this._angle / 2.0);
  47663. var A = 1.0;
  47664. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  47665. };
  47666. /**
  47667. * Main function for light texture projection matrix computing.
  47668. */
  47669. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  47670. this._projectionTextureDirty = false;
  47671. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  47672. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  47673. };
  47674. SpotLight.prototype._buildUniformLayout = function () {
  47675. this._uniformBuffer.addUniform("vLightData", 4);
  47676. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47677. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47678. this._uniformBuffer.addUniform("vLightDirection", 3);
  47679. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47680. this._uniformBuffer.addUniform("depthValues", 2);
  47681. this._uniformBuffer.create();
  47682. };
  47683. /**
  47684. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  47685. * @param effect The effect to update
  47686. * @param lightIndex The index of the light in the effect to update
  47687. * @returns The spot light
  47688. */
  47689. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  47690. var normalizeDirection;
  47691. if (this.computeTransformedInformation()) {
  47692. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  47693. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  47694. }
  47695. else {
  47696. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  47697. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  47698. }
  47699. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  47700. if (this.projectionTexture && this.projectionTexture.isReady()) {
  47701. if (this._projectionTextureViewLightDirty) {
  47702. this._computeProjectionTextureViewLightMatrix();
  47703. }
  47704. if (this._projectionTextureProjectionLightDirty) {
  47705. this._computeProjectionTextureProjectionLightMatrix();
  47706. }
  47707. if (this._projectionTextureDirty) {
  47708. this._computeProjectionTextureMatrix();
  47709. }
  47710. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  47711. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  47712. }
  47713. return this;
  47714. };
  47715. /**
  47716. * Disposes the light and the associated resources.
  47717. */
  47718. SpotLight.prototype.dispose = function () {
  47719. _super.prototype.dispose.call(this);
  47720. if (this._projectionTexture) {
  47721. this._projectionTexture.dispose();
  47722. }
  47723. };
  47724. __decorate([
  47725. BABYLON.serialize()
  47726. ], SpotLight.prototype, "angle", null);
  47727. __decorate([
  47728. BABYLON.serialize()
  47729. ], SpotLight.prototype, "shadowAngleScale", null);
  47730. __decorate([
  47731. BABYLON.serialize()
  47732. ], SpotLight.prototype, "exponent", void 0);
  47733. __decorate([
  47734. BABYLON.serialize()
  47735. ], SpotLight.prototype, "projectionTextureLightNear", null);
  47736. __decorate([
  47737. BABYLON.serialize()
  47738. ], SpotLight.prototype, "projectionTextureLightFar", null);
  47739. __decorate([
  47740. BABYLON.serialize()
  47741. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  47742. __decorate([
  47743. BABYLON.serializeAsTexture("projectedLightTexture")
  47744. ], SpotLight.prototype, "_projectionTexture", void 0);
  47745. return SpotLight;
  47746. }(BABYLON.ShadowLight));
  47747. BABYLON.SpotLight = SpotLight;
  47748. })(BABYLON || (BABYLON = {}));
  47749. //# sourceMappingURL=babylon.spotLight.js.map
  47750. "use strict";
  47751. var BABYLON;
  47752. (function (BABYLON) {
  47753. /**
  47754. * Class used to override all child animations of a given target
  47755. */
  47756. var AnimationPropertiesOverride = /** @class */ (function () {
  47757. function AnimationPropertiesOverride() {
  47758. /**
  47759. * Gets or sets a value indicating if animation blending must be used
  47760. */
  47761. this.enableBlending = false;
  47762. /**
  47763. * Gets or sets the blending speed to use when enableBlending is true
  47764. */
  47765. this.blendingSpeed = 0.01;
  47766. /**
  47767. * Gets or sets the default loop mode to use
  47768. */
  47769. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  47770. }
  47771. return AnimationPropertiesOverride;
  47772. }());
  47773. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  47774. })(BABYLON || (BABYLON = {}));
  47775. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  47776. "use strict";
  47777. var BABYLON;
  47778. (function (BABYLON) {
  47779. var AnimationRange = /** @class */ (function () {
  47780. function AnimationRange(name, from, to) {
  47781. this.name = name;
  47782. this.from = from;
  47783. this.to = to;
  47784. }
  47785. AnimationRange.prototype.clone = function () {
  47786. return new AnimationRange(this.name, this.from, this.to);
  47787. };
  47788. return AnimationRange;
  47789. }());
  47790. BABYLON.AnimationRange = AnimationRange;
  47791. /**
  47792. * Composed of a frame, and an action function
  47793. */
  47794. var AnimationEvent = /** @class */ (function () {
  47795. function AnimationEvent(frame, action, onlyOnce) {
  47796. this.frame = frame;
  47797. this.action = action;
  47798. this.onlyOnce = onlyOnce;
  47799. this.isDone = false;
  47800. }
  47801. return AnimationEvent;
  47802. }());
  47803. BABYLON.AnimationEvent = AnimationEvent;
  47804. var PathCursor = /** @class */ (function () {
  47805. function PathCursor(path) {
  47806. this.path = path;
  47807. this._onchange = new Array();
  47808. this.value = 0;
  47809. this.animations = new Array();
  47810. }
  47811. PathCursor.prototype.getPoint = function () {
  47812. var point = this.path.getPointAtLengthPosition(this.value);
  47813. return new BABYLON.Vector3(point.x, 0, point.y);
  47814. };
  47815. PathCursor.prototype.moveAhead = function (step) {
  47816. if (step === void 0) { step = 0.002; }
  47817. this.move(step);
  47818. return this;
  47819. };
  47820. PathCursor.prototype.moveBack = function (step) {
  47821. if (step === void 0) { step = 0.002; }
  47822. this.move(-step);
  47823. return this;
  47824. };
  47825. PathCursor.prototype.move = function (step) {
  47826. if (Math.abs(step) > 1) {
  47827. throw "step size should be less than 1.";
  47828. }
  47829. this.value += step;
  47830. this.ensureLimits();
  47831. this.raiseOnChange();
  47832. return this;
  47833. };
  47834. PathCursor.prototype.ensureLimits = function () {
  47835. while (this.value > 1) {
  47836. this.value -= 1;
  47837. }
  47838. while (this.value < 0) {
  47839. this.value += 1;
  47840. }
  47841. return this;
  47842. };
  47843. // used by animation engine
  47844. PathCursor.prototype.raiseOnChange = function () {
  47845. var _this = this;
  47846. this._onchange.forEach(function (f) { return f(_this); });
  47847. return this;
  47848. };
  47849. PathCursor.prototype.onchange = function (f) {
  47850. this._onchange.push(f);
  47851. return this;
  47852. };
  47853. return PathCursor;
  47854. }());
  47855. BABYLON.PathCursor = PathCursor;
  47856. var AnimationKeyInterpolation;
  47857. (function (AnimationKeyInterpolation) {
  47858. /**
  47859. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  47860. */
  47861. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  47862. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  47863. var Animation = /** @class */ (function () {
  47864. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  47865. this.name = name;
  47866. this.targetProperty = targetProperty;
  47867. this.framePerSecond = framePerSecond;
  47868. this.dataType = dataType;
  47869. this.loopMode = loopMode;
  47870. this.enableBlending = enableBlending;
  47871. this._runtimeAnimations = new Array();
  47872. // The set of event that will be linked to this animation
  47873. this._events = new Array();
  47874. this.blendingSpeed = 0.01;
  47875. this._ranges = {};
  47876. this.targetPropertyPath = targetProperty.split(".");
  47877. this.dataType = dataType;
  47878. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  47879. }
  47880. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  47881. var dataType = undefined;
  47882. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  47883. dataType = Animation.ANIMATIONTYPE_FLOAT;
  47884. }
  47885. else if (from instanceof BABYLON.Quaternion) {
  47886. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  47887. }
  47888. else if (from instanceof BABYLON.Vector3) {
  47889. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  47890. }
  47891. else if (from instanceof BABYLON.Vector2) {
  47892. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  47893. }
  47894. else if (from instanceof BABYLON.Color3) {
  47895. dataType = Animation.ANIMATIONTYPE_COLOR3;
  47896. }
  47897. else if (from instanceof BABYLON.Size) {
  47898. dataType = Animation.ANIMATIONTYPE_SIZE;
  47899. }
  47900. if (dataType == undefined) {
  47901. return null;
  47902. }
  47903. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  47904. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  47905. animation.setKeys(keys);
  47906. if (easingFunction !== undefined) {
  47907. animation.setEasingFunction(easingFunction);
  47908. }
  47909. return animation;
  47910. };
  47911. /**
  47912. * Sets up an animation.
  47913. * @param property the property to animate
  47914. * @param animationType the animation type to apply
  47915. * @param easingFunction the easing function used in the animation
  47916. * @returns The created animation
  47917. */
  47918. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  47919. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  47920. animation.setEasingFunction(easingFunction);
  47921. return animation;
  47922. };
  47923. /**
  47924. * Create and start an animation on a node
  47925. * @param {string} name defines the name of the global animation that will be run on all nodes
  47926. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47927. * @param {string} targetProperty defines property to animate
  47928. * @param {number} framePerSecond defines the number of frame per second yo use
  47929. * @param {number} totalFrame defines the number of frames in total
  47930. * @param {any} from defines the initial value
  47931. * @param {any} to defines the final value
  47932. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47933. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47934. * @param onAnimationEnd defines the callback to call when animation end
  47935. * @returns the animatable created for this animation
  47936. */
  47937. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47938. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47939. if (!animation) {
  47940. return null;
  47941. }
  47942. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47943. };
  47944. /**
  47945. * Create and start an animation on a node and its descendants
  47946. * @param {string} name defines the name of the global animation that will be run on all nodes
  47947. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47948. * @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.
  47949. * @param {string} targetProperty defines property to animate
  47950. * @param {number} framePerSecond defines the number of frame per second yo use
  47951. * @param {number} totalFrame defines the number of frames in total
  47952. * @param {any} from defines the initial value
  47953. * @param {any} to defines the final value
  47954. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47955. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47956. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47957. * @returns the list of animatables created for all nodes
  47958. * @example https://www.babylonjs-playground.com/#MH0VLI
  47959. */
  47960. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47961. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47962. if (!animation) {
  47963. return null;
  47964. }
  47965. var scene = node.getScene();
  47966. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47967. };
  47968. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47969. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47970. if (!animation) {
  47971. return null;
  47972. }
  47973. node.animations.push(animation);
  47974. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47975. };
  47976. /**
  47977. * Transition property of the Camera to the target Value.
  47978. * @param property The property to transition
  47979. * @param targetValue The target Value of the property
  47980. * @param host The object where the property to animate belongs
  47981. * @param scene Scene used to run the animation
  47982. * @param frameRate Framerate (in frame/s) to use
  47983. * @param transition The transition type we want to use
  47984. * @param duration The duration of the animation, in milliseconds
  47985. * @param onAnimationEnd Call back trigger at the end of the animation.
  47986. */
  47987. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47988. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47989. if (duration <= 0) {
  47990. host[property] = targetValue;
  47991. if (onAnimationEnd) {
  47992. onAnimationEnd();
  47993. }
  47994. return null;
  47995. }
  47996. var endFrame = frameRate * (duration / 1000);
  47997. transition.setKeys([{
  47998. frame: 0,
  47999. value: host[property].clone ? host[property].clone() : host[property]
  48000. },
  48001. {
  48002. frame: endFrame,
  48003. value: targetValue
  48004. }]);
  48005. if (!host.animations) {
  48006. host.animations = [];
  48007. }
  48008. host.animations.push(transition);
  48009. var animation = scene.beginAnimation(host, 0, endFrame, false);
  48010. animation.onAnimationEnd = onAnimationEnd;
  48011. return animation;
  48012. };
  48013. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  48014. /**
  48015. * Return the array of runtime animations currently using this animation
  48016. */
  48017. get: function () {
  48018. return this._runtimeAnimations;
  48019. },
  48020. enumerable: true,
  48021. configurable: true
  48022. });
  48023. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  48024. get: function () {
  48025. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  48026. var runtimeAnimation = _a[_i];
  48027. if (!runtimeAnimation.isStopped) {
  48028. return true;
  48029. }
  48030. }
  48031. return false;
  48032. },
  48033. enumerable: true,
  48034. configurable: true
  48035. });
  48036. // Methods
  48037. /**
  48038. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  48039. */
  48040. Animation.prototype.toString = function (fullDetails) {
  48041. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  48042. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  48043. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  48044. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  48045. if (fullDetails) {
  48046. ret += ", Ranges: {";
  48047. var first = true;
  48048. for (var name in this._ranges) {
  48049. if (first) {
  48050. ret += ", ";
  48051. first = false;
  48052. }
  48053. ret += name;
  48054. }
  48055. ret += "}";
  48056. }
  48057. return ret;
  48058. };
  48059. /**
  48060. * Add an event to this animation.
  48061. */
  48062. Animation.prototype.addEvent = function (event) {
  48063. this._events.push(event);
  48064. };
  48065. /**
  48066. * Remove all events found at the given frame
  48067. * @param frame
  48068. */
  48069. Animation.prototype.removeEvents = function (frame) {
  48070. for (var index = 0; index < this._events.length; index++) {
  48071. if (this._events[index].frame === frame) {
  48072. this._events.splice(index, 1);
  48073. index--;
  48074. }
  48075. }
  48076. };
  48077. Animation.prototype.getEvents = function () {
  48078. return this._events;
  48079. };
  48080. Animation.prototype.createRange = function (name, from, to) {
  48081. // check name not already in use; could happen for bones after serialized
  48082. if (!this._ranges[name]) {
  48083. this._ranges[name] = new AnimationRange(name, from, to);
  48084. }
  48085. };
  48086. Animation.prototype.deleteRange = function (name, deleteFrames) {
  48087. if (deleteFrames === void 0) { deleteFrames = true; }
  48088. var range = this._ranges[name];
  48089. if (!range) {
  48090. return;
  48091. }
  48092. if (deleteFrames) {
  48093. var from = range.from;
  48094. var to = range.to;
  48095. // this loop MUST go high to low for multiple splices to work
  48096. for (var key = this._keys.length - 1; key >= 0; key--) {
  48097. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  48098. this._keys.splice(key, 1);
  48099. }
  48100. }
  48101. }
  48102. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  48103. };
  48104. Animation.prototype.getRange = function (name) {
  48105. return this._ranges[name];
  48106. };
  48107. Animation.prototype.getKeys = function () {
  48108. return this._keys;
  48109. };
  48110. Animation.prototype.getHighestFrame = function () {
  48111. var ret = 0;
  48112. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  48113. if (ret < this._keys[key].frame) {
  48114. ret = this._keys[key].frame;
  48115. }
  48116. }
  48117. return ret;
  48118. };
  48119. Animation.prototype.getEasingFunction = function () {
  48120. return this._easingFunction;
  48121. };
  48122. Animation.prototype.setEasingFunction = function (easingFunction) {
  48123. this._easingFunction = easingFunction;
  48124. };
  48125. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  48126. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  48127. };
  48128. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  48129. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  48130. };
  48131. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  48132. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  48133. };
  48134. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  48135. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  48136. };
  48137. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  48138. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  48139. };
  48140. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  48141. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  48142. };
  48143. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  48144. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  48145. };
  48146. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  48147. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  48148. };
  48149. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  48150. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  48151. };
  48152. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  48153. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  48154. };
  48155. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  48156. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  48157. };
  48158. Animation.prototype.clone = function () {
  48159. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  48160. clone.enableBlending = this.enableBlending;
  48161. clone.blendingSpeed = this.blendingSpeed;
  48162. if (this._keys) {
  48163. clone.setKeys(this._keys);
  48164. }
  48165. if (this._ranges) {
  48166. clone._ranges = {};
  48167. for (var name in this._ranges) {
  48168. var range = this._ranges[name];
  48169. if (!range) {
  48170. continue;
  48171. }
  48172. clone._ranges[name] = range.clone();
  48173. }
  48174. }
  48175. return clone;
  48176. };
  48177. Animation.prototype.setKeys = function (values) {
  48178. this._keys = values.slice(0);
  48179. };
  48180. Animation.prototype.serialize = function () {
  48181. var serializationObject = {};
  48182. serializationObject.name = this.name;
  48183. serializationObject.property = this.targetProperty;
  48184. serializationObject.framePerSecond = this.framePerSecond;
  48185. serializationObject.dataType = this.dataType;
  48186. serializationObject.loopBehavior = this.loopMode;
  48187. serializationObject.enableBlending = this.enableBlending;
  48188. serializationObject.blendingSpeed = this.blendingSpeed;
  48189. var dataType = this.dataType;
  48190. serializationObject.keys = [];
  48191. var keys = this.getKeys();
  48192. for (var index = 0; index < keys.length; index++) {
  48193. var animationKey = keys[index];
  48194. var key = {};
  48195. key.frame = animationKey.frame;
  48196. switch (dataType) {
  48197. case Animation.ANIMATIONTYPE_FLOAT:
  48198. key.values = [animationKey.value];
  48199. break;
  48200. case Animation.ANIMATIONTYPE_QUATERNION:
  48201. case Animation.ANIMATIONTYPE_MATRIX:
  48202. case Animation.ANIMATIONTYPE_VECTOR3:
  48203. case Animation.ANIMATIONTYPE_COLOR3:
  48204. key.values = animationKey.value.asArray();
  48205. break;
  48206. }
  48207. serializationObject.keys.push(key);
  48208. }
  48209. serializationObject.ranges = [];
  48210. for (var name in this._ranges) {
  48211. var source = this._ranges[name];
  48212. if (!source) {
  48213. continue;
  48214. }
  48215. var range = {};
  48216. range.name = name;
  48217. range.from = source.from;
  48218. range.to = source.to;
  48219. serializationObject.ranges.push(range);
  48220. }
  48221. return serializationObject;
  48222. };
  48223. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  48224. get: function () {
  48225. return Animation._ANIMATIONTYPE_FLOAT;
  48226. },
  48227. enumerable: true,
  48228. configurable: true
  48229. });
  48230. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  48231. get: function () {
  48232. return Animation._ANIMATIONTYPE_VECTOR3;
  48233. },
  48234. enumerable: true,
  48235. configurable: true
  48236. });
  48237. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  48238. get: function () {
  48239. return Animation._ANIMATIONTYPE_VECTOR2;
  48240. },
  48241. enumerable: true,
  48242. configurable: true
  48243. });
  48244. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  48245. get: function () {
  48246. return Animation._ANIMATIONTYPE_SIZE;
  48247. },
  48248. enumerable: true,
  48249. configurable: true
  48250. });
  48251. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  48252. get: function () {
  48253. return Animation._ANIMATIONTYPE_QUATERNION;
  48254. },
  48255. enumerable: true,
  48256. configurable: true
  48257. });
  48258. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  48259. get: function () {
  48260. return Animation._ANIMATIONTYPE_MATRIX;
  48261. },
  48262. enumerable: true,
  48263. configurable: true
  48264. });
  48265. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  48266. get: function () {
  48267. return Animation._ANIMATIONTYPE_COLOR3;
  48268. },
  48269. enumerable: true,
  48270. configurable: true
  48271. });
  48272. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  48273. get: function () {
  48274. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  48275. },
  48276. enumerable: true,
  48277. configurable: true
  48278. });
  48279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  48280. get: function () {
  48281. return Animation._ANIMATIONLOOPMODE_CYCLE;
  48282. },
  48283. enumerable: true,
  48284. configurable: true
  48285. });
  48286. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  48287. get: function () {
  48288. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  48289. },
  48290. enumerable: true,
  48291. configurable: true
  48292. });
  48293. Animation.Parse = function (parsedAnimation) {
  48294. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  48295. var dataType = parsedAnimation.dataType;
  48296. var keys = [];
  48297. var data;
  48298. var index;
  48299. if (parsedAnimation.enableBlending) {
  48300. animation.enableBlending = parsedAnimation.enableBlending;
  48301. }
  48302. if (parsedAnimation.blendingSpeed) {
  48303. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  48304. }
  48305. for (index = 0; index < parsedAnimation.keys.length; index++) {
  48306. var key = parsedAnimation.keys[index];
  48307. var inTangent;
  48308. var outTangent;
  48309. switch (dataType) {
  48310. case Animation.ANIMATIONTYPE_FLOAT:
  48311. data = key.values[0];
  48312. if (key.values.length >= 1) {
  48313. inTangent = key.values[1];
  48314. }
  48315. if (key.values.length >= 2) {
  48316. outTangent = key.values[2];
  48317. }
  48318. break;
  48319. case Animation.ANIMATIONTYPE_QUATERNION:
  48320. data = BABYLON.Quaternion.FromArray(key.values);
  48321. if (key.values.length >= 8) {
  48322. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  48323. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  48324. inTangent = _inTangent;
  48325. }
  48326. }
  48327. if (key.values.length >= 12) {
  48328. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  48329. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  48330. outTangent = _outTangent;
  48331. }
  48332. }
  48333. break;
  48334. case Animation.ANIMATIONTYPE_MATRIX:
  48335. data = BABYLON.Matrix.FromArray(key.values);
  48336. break;
  48337. case Animation.ANIMATIONTYPE_COLOR3:
  48338. data = BABYLON.Color3.FromArray(key.values);
  48339. break;
  48340. case Animation.ANIMATIONTYPE_VECTOR3:
  48341. default:
  48342. data = BABYLON.Vector3.FromArray(key.values);
  48343. break;
  48344. }
  48345. var keyData = {};
  48346. keyData.frame = key.frame;
  48347. keyData.value = data;
  48348. if (inTangent != undefined) {
  48349. keyData.inTangent = inTangent;
  48350. }
  48351. if (outTangent != undefined) {
  48352. keyData.outTangent = outTangent;
  48353. }
  48354. keys.push(keyData);
  48355. }
  48356. animation.setKeys(keys);
  48357. if (parsedAnimation.ranges) {
  48358. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  48359. data = parsedAnimation.ranges[index];
  48360. animation.createRange(data.name, data.from, data.to);
  48361. }
  48362. }
  48363. return animation;
  48364. };
  48365. Animation.AppendSerializedAnimations = function (source, destination) {
  48366. if (source.animations) {
  48367. destination.animations = [];
  48368. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  48369. var animation = source.animations[animationIndex];
  48370. destination.animations.push(animation.serialize());
  48371. }
  48372. }
  48373. };
  48374. Animation.AllowMatricesInterpolation = false;
  48375. // Statics
  48376. Animation._ANIMATIONTYPE_FLOAT = 0;
  48377. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  48378. Animation._ANIMATIONTYPE_QUATERNION = 2;
  48379. Animation._ANIMATIONTYPE_MATRIX = 3;
  48380. Animation._ANIMATIONTYPE_COLOR3 = 4;
  48381. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  48382. Animation._ANIMATIONTYPE_SIZE = 6;
  48383. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  48384. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  48385. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  48386. return Animation;
  48387. }());
  48388. BABYLON.Animation = Animation;
  48389. })(BABYLON || (BABYLON = {}));
  48390. //# sourceMappingURL=babylon.animation.js.map
  48391. "use strict";
  48392. var BABYLON;
  48393. (function (BABYLON) {
  48394. /**
  48395. * This class defines the direct association between an animation and a target
  48396. */
  48397. var TargetedAnimation = /** @class */ (function () {
  48398. function TargetedAnimation() {
  48399. }
  48400. return TargetedAnimation;
  48401. }());
  48402. BABYLON.TargetedAnimation = TargetedAnimation;
  48403. /**
  48404. * Use this class to create coordinated animations on multiple targets
  48405. */
  48406. var AnimationGroup = /** @class */ (function () {
  48407. function AnimationGroup(name, scene) {
  48408. if (scene === void 0) { scene = null; }
  48409. this.name = name;
  48410. this._targetedAnimations = new Array();
  48411. this._animatables = new Array();
  48412. this._from = Number.MAX_VALUE;
  48413. this._to = -Number.MAX_VALUE;
  48414. this._speedRatio = 1;
  48415. this.onAnimationEndObservable = new BABYLON.Observable();
  48416. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48417. this._scene.animationGroups.push(this);
  48418. }
  48419. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  48420. /**
  48421. * Define if the animations are started
  48422. */
  48423. get: function () {
  48424. return this._isStarted;
  48425. },
  48426. enumerable: true,
  48427. configurable: true
  48428. });
  48429. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  48430. /**
  48431. * Gets or sets the speed ratio to use for all animations
  48432. */
  48433. get: function () {
  48434. return this._speedRatio;
  48435. },
  48436. /**
  48437. * Gets or sets the speed ratio to use for all animations
  48438. */
  48439. set: function (value) {
  48440. if (this._speedRatio === value) {
  48441. return;
  48442. }
  48443. this._speedRatio = value;
  48444. for (var index = 0; index < this._animatables.length; index++) {
  48445. var animatable = this._animatables[index];
  48446. animatable.speedRatio = this._speedRatio;
  48447. }
  48448. },
  48449. enumerable: true,
  48450. configurable: true
  48451. });
  48452. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  48453. /**
  48454. * Gets the targeted animations for this animation group
  48455. */
  48456. get: function () {
  48457. return this._targetedAnimations;
  48458. },
  48459. enumerable: true,
  48460. configurable: true
  48461. });
  48462. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  48463. /**
  48464. * returning the list of animatables controlled by this animation group.
  48465. */
  48466. get: function () {
  48467. return this._animatables;
  48468. },
  48469. enumerable: true,
  48470. configurable: true
  48471. });
  48472. /**
  48473. * Add an animation (with its target) in the group
  48474. * @param animation defines the animation we want to add
  48475. * @param target defines the target of the animation
  48476. * @returns the {BABYLON.TargetedAnimation} object
  48477. */
  48478. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  48479. var targetedAnimation = {
  48480. animation: animation,
  48481. target: target
  48482. };
  48483. var keys = animation.getKeys();
  48484. if (this._from > keys[0].frame) {
  48485. this._from = keys[0].frame;
  48486. }
  48487. if (this._to < keys[keys.length - 1].frame) {
  48488. this._to = keys[keys.length - 1].frame;
  48489. }
  48490. this._targetedAnimations.push(targetedAnimation);
  48491. return targetedAnimation;
  48492. };
  48493. /**
  48494. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  48495. * It can add constant keys at begin or end
  48496. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  48497. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  48498. */
  48499. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  48500. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  48501. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  48502. beginFrame = Math.max(beginFrame, this._from);
  48503. endFrame = Math.min(endFrame, this._to);
  48504. for (var index = 0; index < this._targetedAnimations.length; index++) {
  48505. var targetedAnimation = this._targetedAnimations[index];
  48506. var keys = targetedAnimation.animation.getKeys();
  48507. var startKey = keys[0];
  48508. var endKey = keys[keys.length - 1];
  48509. if (startKey.frame > beginFrame) {
  48510. var newKey = {
  48511. frame: beginFrame,
  48512. value: startKey.value,
  48513. inTangent: startKey.inTangent,
  48514. outTangent: startKey.outTangent,
  48515. interpolation: startKey.interpolation
  48516. };
  48517. keys.splice(0, 0, newKey);
  48518. }
  48519. if (endKey.frame < endFrame) {
  48520. var newKey = {
  48521. frame: endFrame,
  48522. value: endKey.value,
  48523. inTangent: endKey.outTangent,
  48524. outTangent: endKey.outTangent,
  48525. interpolation: endKey.interpolation
  48526. };
  48527. keys.push(newKey);
  48528. }
  48529. }
  48530. return this;
  48531. };
  48532. /**
  48533. * Start all animations on given targets
  48534. * @param loop defines if animations must loop
  48535. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  48536. * @param from defines the from key (optional)
  48537. * @param to defines the to key (optional)
  48538. * @returns the current animation group
  48539. */
  48540. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  48541. var _this = this;
  48542. if (loop === void 0) { loop = false; }
  48543. if (speedRatio === void 0) { speedRatio = 1; }
  48544. if (this._isStarted || this._targetedAnimations.length === 0) {
  48545. return this;
  48546. }
  48547. var _loop_1 = function () {
  48548. var targetedAnimation = this_1._targetedAnimations[index];
  48549. if (!targetedAnimation.target.animations) {
  48550. targetedAnimation.target.animations = [];
  48551. }
  48552. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  48553. targetedAnimation.target.animations.push(targetedAnimation.animation);
  48554. }
  48555. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  48556. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  48557. }));
  48558. };
  48559. var this_1 = this;
  48560. for (var index = 0; index < this._targetedAnimations.length; index++) {
  48561. _loop_1();
  48562. }
  48563. this._speedRatio = speedRatio;
  48564. this._isStarted = true;
  48565. return this;
  48566. };
  48567. /**
  48568. * Pause all animations
  48569. */
  48570. AnimationGroup.prototype.pause = function () {
  48571. if (!this._isStarted) {
  48572. return this;
  48573. }
  48574. for (var index = 0; index < this._animatables.length; index++) {
  48575. var animatable = this._animatables[index];
  48576. animatable.pause();
  48577. }
  48578. return this;
  48579. };
  48580. /**
  48581. * Play all animations to initial state
  48582. * This function will start() the animations if they were not started or will restart() them if they were paused
  48583. * @param loop defines if animations must loop
  48584. */
  48585. AnimationGroup.prototype.play = function (loop) {
  48586. if (this.isStarted) {
  48587. if (loop !== undefined) {
  48588. for (var index = 0; index < this._animatables.length; index++) {
  48589. var animatable = this._animatables[index];
  48590. animatable.loopAnimation = loop;
  48591. }
  48592. }
  48593. this.restart();
  48594. }
  48595. else {
  48596. this.start(loop, this._speedRatio);
  48597. }
  48598. return this;
  48599. };
  48600. /**
  48601. * Reset all animations to initial state
  48602. */
  48603. AnimationGroup.prototype.reset = function () {
  48604. if (!this._isStarted) {
  48605. return this;
  48606. }
  48607. for (var index = 0; index < this._animatables.length; index++) {
  48608. var animatable = this._animatables[index];
  48609. animatable.reset();
  48610. }
  48611. return this;
  48612. };
  48613. /**
  48614. * Restart animations from key 0
  48615. */
  48616. AnimationGroup.prototype.restart = function () {
  48617. if (!this._isStarted) {
  48618. return this;
  48619. }
  48620. for (var index = 0; index < this._animatables.length; index++) {
  48621. var animatable = this._animatables[index];
  48622. animatable.restart();
  48623. }
  48624. return this;
  48625. };
  48626. /**
  48627. * Stop all animations
  48628. */
  48629. AnimationGroup.prototype.stop = function () {
  48630. if (!this._isStarted) {
  48631. return this;
  48632. }
  48633. for (var index = 0; index < this._animatables.length; index++) {
  48634. var animatable = this._animatables[index];
  48635. animatable.stop();
  48636. }
  48637. this._isStarted = false;
  48638. return this;
  48639. };
  48640. /**
  48641. * Goes to a specific frame in this animation group
  48642. *
  48643. * @param frame the frame number to go to
  48644. * @return the animationGroup
  48645. */
  48646. AnimationGroup.prototype.goToFrame = function (frame) {
  48647. if (!this._isStarted) {
  48648. return this;
  48649. }
  48650. for (var index = 0; index < this._animatables.length; index++) {
  48651. var animatable = this._animatables[index];
  48652. animatable.goToFrame(frame);
  48653. }
  48654. return this;
  48655. };
  48656. /**
  48657. * Dispose all associated resources
  48658. */
  48659. AnimationGroup.prototype.dispose = function () {
  48660. this._targetedAnimations = [];
  48661. this._animatables = [];
  48662. var index = this._scene.animationGroups.indexOf(this);
  48663. if (index > -1) {
  48664. this._scene.animationGroups.splice(index, 1);
  48665. }
  48666. };
  48667. return AnimationGroup;
  48668. }());
  48669. BABYLON.AnimationGroup = AnimationGroup;
  48670. })(BABYLON || (BABYLON = {}));
  48671. //# sourceMappingURL=babylon.animationGroup.js.map
  48672. "use strict";
  48673. var BABYLON;
  48674. (function (BABYLON) {
  48675. var RuntimeAnimation = /** @class */ (function () {
  48676. /**
  48677. * Create a new RuntimeAnimation object
  48678. * @param target defines the target of the animation
  48679. * @param animation defines the source {BABYLON.Animation} object
  48680. * @param scene defines the hosting scene
  48681. * @param host defines the initiating Animatable
  48682. */
  48683. function RuntimeAnimation(target, animation, scene, host) {
  48684. this._currentFrame = 0;
  48685. this._offsetsCache = {};
  48686. this._highLimitsCache = {};
  48687. this._stopped = false;
  48688. this._blendingFactor = 0;
  48689. this._targetPath = "";
  48690. this._weight = 1.0;
  48691. this._ratioOffset = 0;
  48692. this._previousDelay = 0;
  48693. this._previousRatio = 0;
  48694. this._animation = animation;
  48695. this._target = target;
  48696. this._scene = scene;
  48697. this._host = host;
  48698. animation._runtimeAnimations.push(this);
  48699. }
  48700. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  48701. /**
  48702. * Gets the current frame
  48703. */
  48704. get: function () {
  48705. return this._currentFrame;
  48706. },
  48707. enumerable: true,
  48708. configurable: true
  48709. });
  48710. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  48711. /**
  48712. * Gets the weight of the runtime animation
  48713. */
  48714. get: function () {
  48715. return this._weight;
  48716. },
  48717. enumerable: true,
  48718. configurable: true
  48719. });
  48720. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  48721. /**
  48722. * Gets the original value of the runtime animation
  48723. */
  48724. get: function () {
  48725. return this._originalValue;
  48726. },
  48727. enumerable: true,
  48728. configurable: true
  48729. });
  48730. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  48731. /**
  48732. * Gets the current value of the runtime animation
  48733. */
  48734. get: function () {
  48735. return this._currentValue;
  48736. },
  48737. enumerable: true,
  48738. configurable: true
  48739. });
  48740. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  48741. /**
  48742. * Gets the path where to store the animated value in the target
  48743. */
  48744. get: function () {
  48745. return this._targetPath;
  48746. },
  48747. enumerable: true,
  48748. configurable: true
  48749. });
  48750. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  48751. /**
  48752. * Gets the actual target of the runtime animation
  48753. */
  48754. get: function () {
  48755. return this._activeTarget;
  48756. },
  48757. enumerable: true,
  48758. configurable: true
  48759. });
  48760. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  48761. get: function () {
  48762. return this._animation;
  48763. },
  48764. enumerable: true,
  48765. configurable: true
  48766. });
  48767. RuntimeAnimation.prototype.reset = function () {
  48768. this._offsetsCache = {};
  48769. this._highLimitsCache = {};
  48770. this._currentFrame = 0;
  48771. this._blendingFactor = 0;
  48772. this._originalValue = null;
  48773. };
  48774. RuntimeAnimation.prototype.isStopped = function () {
  48775. return this._stopped;
  48776. };
  48777. RuntimeAnimation.prototype.dispose = function () {
  48778. var index = this._animation.runtimeAnimations.indexOf(this);
  48779. if (index > -1) {
  48780. this._animation.runtimeAnimations.splice(index, 1);
  48781. }
  48782. };
  48783. RuntimeAnimation.prototype._getKeyValue = function (value) {
  48784. if (typeof value === "function") {
  48785. return value();
  48786. }
  48787. return value;
  48788. };
  48789. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  48790. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  48791. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  48792. }
  48793. this._currentFrame = currentFrame;
  48794. var keys = this._animation.getKeys();
  48795. // Try to get a hash to find the right key
  48796. 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));
  48797. if (keys[startKeyIndex].frame >= currentFrame) {
  48798. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  48799. startKeyIndex--;
  48800. }
  48801. }
  48802. for (var key = startKeyIndex; key < keys.length; key++) {
  48803. var endKey = keys[key + 1];
  48804. if (endKey.frame >= currentFrame) {
  48805. var startKey = keys[key];
  48806. var startValue = this._getKeyValue(startKey.value);
  48807. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  48808. return startValue;
  48809. }
  48810. var endValue = this._getKeyValue(endKey.value);
  48811. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  48812. var frameDelta = endKey.frame - startKey.frame;
  48813. // gradient : percent of currentFrame between the frame inf and the frame sup
  48814. var gradient = (currentFrame - startKey.frame) / frameDelta;
  48815. // check for easingFunction and correction of gradient
  48816. var easingFunction = this._animation.getEasingFunction();
  48817. if (easingFunction != null) {
  48818. gradient = easingFunction.ease(gradient);
  48819. }
  48820. switch (this._animation.dataType) {
  48821. // Float
  48822. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48823. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  48824. switch (loopMode) {
  48825. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48826. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48827. return floatValue;
  48828. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48829. return offsetValue * repeatCount + floatValue;
  48830. }
  48831. break;
  48832. // Quaternion
  48833. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48834. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  48835. switch (loopMode) {
  48836. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48837. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48838. return quatValue;
  48839. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48840. return quatValue.add(offsetValue.scale(repeatCount));
  48841. }
  48842. return quatValue;
  48843. // Vector3
  48844. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48845. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  48846. switch (loopMode) {
  48847. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48848. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48849. return vec3Value;
  48850. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48851. return vec3Value.add(offsetValue.scale(repeatCount));
  48852. }
  48853. // Vector2
  48854. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48855. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  48856. switch (loopMode) {
  48857. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48858. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48859. return vec2Value;
  48860. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48861. return vec2Value.add(offsetValue.scale(repeatCount));
  48862. }
  48863. // Size
  48864. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48865. switch (loopMode) {
  48866. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48867. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48868. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  48869. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48870. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  48871. }
  48872. // Color3
  48873. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48874. switch (loopMode) {
  48875. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48876. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48877. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  48878. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48879. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  48880. }
  48881. // Matrix
  48882. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  48883. switch (loopMode) {
  48884. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48885. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48886. if (BABYLON.Animation.AllowMatricesInterpolation) {
  48887. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  48888. }
  48889. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48890. return startValue;
  48891. }
  48892. default:
  48893. break;
  48894. }
  48895. break;
  48896. }
  48897. }
  48898. return this._getKeyValue(keys[keys.length - 1].value);
  48899. };
  48900. /**
  48901. * Affect the interpolated value to the target
  48902. * @param currentValue defines the value computed by the animation
  48903. * @param weight defines the weight to apply to this value
  48904. */
  48905. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  48906. if (weight === void 0) { weight = 1.0; }
  48907. // Set value
  48908. var path;
  48909. var destination;
  48910. var targetPropertyPath = this._animation.targetPropertyPath;
  48911. if (targetPropertyPath.length > 1) {
  48912. var property = this._target[targetPropertyPath[0]];
  48913. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  48914. property = property[targetPropertyPath[index]];
  48915. }
  48916. path = targetPropertyPath[targetPropertyPath.length - 1];
  48917. destination = property;
  48918. }
  48919. else {
  48920. path = targetPropertyPath[0];
  48921. destination = this._target;
  48922. }
  48923. this._targetPath = path;
  48924. this._activeTarget = destination;
  48925. this._weight = weight;
  48926. // Blending
  48927. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  48928. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  48929. if (enableBlending && this._blendingFactor <= 1.0) {
  48930. if (!this._originalBlendValue) {
  48931. var originalValue = destination[path];
  48932. if (originalValue.clone) {
  48933. this._originalBlendValue = originalValue.clone();
  48934. }
  48935. else {
  48936. this._originalBlendValue = originalValue;
  48937. }
  48938. }
  48939. }
  48940. if (weight !== -1.0) {
  48941. if (!this._originalValue) {
  48942. var originalValue = void 0;
  48943. if (destination.getRestPose) {
  48944. originalValue = destination.getRestPose();
  48945. }
  48946. else {
  48947. originalValue = destination[path];
  48948. }
  48949. if (originalValue.clone) {
  48950. this._originalValue = originalValue.clone();
  48951. }
  48952. else {
  48953. this._originalValue = originalValue;
  48954. }
  48955. }
  48956. }
  48957. if (enableBlending && this._blendingFactor <= 1.0) {
  48958. if (this._originalBlendValue.prototype) {
  48959. if (this._originalBlendValue.prototype.Lerp) {
  48960. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  48961. }
  48962. else {
  48963. this._currentValue = currentValue;
  48964. }
  48965. }
  48966. else if (this._originalBlendValue.m) {
  48967. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  48968. }
  48969. else {
  48970. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48971. }
  48972. this._blendingFactor += blendingSpeed;
  48973. }
  48974. else {
  48975. this._currentValue = currentValue;
  48976. }
  48977. if (weight !== -1.0) {
  48978. this._scene._registerTargetForLateAnimationBinding(this);
  48979. }
  48980. else {
  48981. destination[path] = this._currentValue;
  48982. }
  48983. if (this._target.markAsDirty) {
  48984. this._target.markAsDirty(this._animation.targetProperty);
  48985. }
  48986. };
  48987. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48988. if (this._target && this._target.animationPropertiesOverride) {
  48989. return this._target.animationPropertiesOverride.loopMode;
  48990. }
  48991. return this._animation.loopMode;
  48992. };
  48993. /**
  48994. * Move the current animation to a given frame
  48995. * @param frame defines the frame to move to
  48996. */
  48997. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48998. var keys = this._animation.getKeys();
  48999. if (frame < keys[0].frame) {
  49000. frame = keys[0].frame;
  49001. }
  49002. else if (frame > keys[keys.length - 1].frame) {
  49003. frame = keys[keys.length - 1].frame;
  49004. }
  49005. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  49006. this.setValue(currentValue, -1);
  49007. };
  49008. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  49009. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  49010. this._ratioOffset = this._previousRatio - newRatio;
  49011. };
  49012. /**
  49013. * Execute the current animation
  49014. * @param delay defines the delay to add to the current frame
  49015. * @param from defines the lower bound of the animation range
  49016. * @param to defines the upper bound of the animation range
  49017. * @param loop defines if the current animation must loop
  49018. * @param speedRatio defines the current speed ratio
  49019. * @param weight defines the weight of the animation (default is -1 so no weight)
  49020. * @returns a boolean indicating if the animation has ended
  49021. */
  49022. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  49023. if (weight === void 0) { weight = -1.0; }
  49024. var targetPropertyPath = this._animation.targetPropertyPath;
  49025. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  49026. this._stopped = true;
  49027. return false;
  49028. }
  49029. var returnValue = true;
  49030. var keys = this._animation.getKeys();
  49031. // Adding a start key at frame 0 if missing
  49032. if (keys[0].frame !== 0) {
  49033. var newKey = { frame: 0, value: keys[0].value };
  49034. keys.splice(0, 0, newKey);
  49035. }
  49036. // Check limits
  49037. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  49038. from = keys[0].frame;
  49039. }
  49040. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  49041. to = keys[keys.length - 1].frame;
  49042. }
  49043. //to and from cannot be the same key
  49044. if (from === to) {
  49045. if (from > keys[0].frame) {
  49046. from--;
  49047. }
  49048. else if (to < keys[keys.length - 1].frame) {
  49049. to++;
  49050. }
  49051. }
  49052. // Compute ratio
  49053. var range = to - from;
  49054. var offsetValue;
  49055. // ratio represents the frame delta between from and to
  49056. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  49057. var highLimitValue = 0;
  49058. this._previousDelay = delay;
  49059. this._previousRatio = ratio;
  49060. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  49061. returnValue = false;
  49062. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  49063. }
  49064. else {
  49065. // Get max value if required
  49066. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  49067. var keyOffset = to.toString() + from.toString();
  49068. if (!this._offsetsCache[keyOffset]) {
  49069. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  49070. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  49071. switch (this._animation.dataType) {
  49072. // Float
  49073. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  49074. this._offsetsCache[keyOffset] = toValue - fromValue;
  49075. break;
  49076. // Quaternion
  49077. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  49078. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  49079. break;
  49080. // Vector3
  49081. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  49082. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  49083. // Vector2
  49084. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  49085. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  49086. // Size
  49087. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  49088. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  49089. // Color3
  49090. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  49091. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  49092. default:
  49093. break;
  49094. }
  49095. this._highLimitsCache[keyOffset] = toValue;
  49096. }
  49097. highLimitValue = this._highLimitsCache[keyOffset];
  49098. offsetValue = this._offsetsCache[keyOffset];
  49099. }
  49100. }
  49101. if (offsetValue === undefined) {
  49102. switch (this._animation.dataType) {
  49103. // Float
  49104. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  49105. offsetValue = 0;
  49106. break;
  49107. // Quaternion
  49108. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  49109. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  49110. break;
  49111. // Vector3
  49112. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  49113. offsetValue = BABYLON.Vector3.Zero();
  49114. break;
  49115. // Vector2
  49116. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  49117. offsetValue = BABYLON.Vector2.Zero();
  49118. break;
  49119. // Size
  49120. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  49121. offsetValue = BABYLON.Size.Zero();
  49122. break;
  49123. // Color3
  49124. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  49125. offsetValue = BABYLON.Color3.Black();
  49126. }
  49127. }
  49128. // Compute value
  49129. var repeatCount = (ratio / range) >> 0;
  49130. var currentFrame = returnValue ? from + ratio % range : to;
  49131. // Need to normalize?
  49132. if (this._host && this._host.syncRoot) {
  49133. var syncRoot = this._host.syncRoot;
  49134. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  49135. currentFrame = from + (to - from) * hostNormalizedFrame;
  49136. }
  49137. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  49138. // Set value
  49139. this.setValue(currentValue, weight);
  49140. // Check events
  49141. var events = this._animation.getEvents();
  49142. for (var index = 0; index < events.length; index++) {
  49143. // Make sure current frame has passed event frame and that event frame is within the current range
  49144. // Also, handle both forward and reverse animations
  49145. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  49146. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  49147. var event = events[index];
  49148. if (!event.isDone) {
  49149. // If event should be done only once, remove it.
  49150. if (event.onlyOnce) {
  49151. events.splice(index, 1);
  49152. index--;
  49153. }
  49154. event.isDone = true;
  49155. event.action();
  49156. } // Don't do anything if the event has already be done.
  49157. }
  49158. else if (events[index].isDone && !events[index].onlyOnce) {
  49159. // reset event, the animation is looping
  49160. events[index].isDone = false;
  49161. }
  49162. }
  49163. if (!returnValue) {
  49164. this._stopped = true;
  49165. }
  49166. return returnValue;
  49167. };
  49168. return RuntimeAnimation;
  49169. }());
  49170. BABYLON.RuntimeAnimation = RuntimeAnimation;
  49171. })(BABYLON || (BABYLON = {}));
  49172. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  49173. "use strict";
  49174. var BABYLON;
  49175. (function (BABYLON) {
  49176. var Animatable = /** @class */ (function () {
  49177. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  49178. if (fromFrame === void 0) { fromFrame = 0; }
  49179. if (toFrame === void 0) { toFrame = 100; }
  49180. if (loopAnimation === void 0) { loopAnimation = false; }
  49181. if (speedRatio === void 0) { speedRatio = 1.0; }
  49182. this.target = target;
  49183. this.fromFrame = fromFrame;
  49184. this.toFrame = toFrame;
  49185. this.loopAnimation = loopAnimation;
  49186. this.onAnimationEnd = onAnimationEnd;
  49187. this._localDelayOffset = null;
  49188. this._pausedDelay = null;
  49189. this._runtimeAnimations = new Array();
  49190. this._paused = false;
  49191. this._speedRatio = 1;
  49192. this._weight = -1.0;
  49193. this.animationStarted = false;
  49194. if (animations) {
  49195. this.appendAnimations(target, animations);
  49196. }
  49197. this._speedRatio = speedRatio;
  49198. this._scene = scene;
  49199. scene._activeAnimatables.push(this);
  49200. }
  49201. Object.defineProperty(Animatable.prototype, "syncRoot", {
  49202. /**
  49203. * Gets the root Animatable used to synchronize and normalize animations
  49204. */
  49205. get: function () {
  49206. return this._syncRoot;
  49207. },
  49208. enumerable: true,
  49209. configurable: true
  49210. });
  49211. Object.defineProperty(Animatable.prototype, "masterFrame", {
  49212. /**
  49213. * Gets the current frame of the first RuntimeAnimation
  49214. * Used to synchronize Animatables
  49215. */
  49216. get: function () {
  49217. if (this._runtimeAnimations.length === 0) {
  49218. return 0;
  49219. }
  49220. return this._runtimeAnimations[0].currentFrame;
  49221. },
  49222. enumerable: true,
  49223. configurable: true
  49224. });
  49225. Object.defineProperty(Animatable.prototype, "weight", {
  49226. /**
  49227. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  49228. */
  49229. get: function () {
  49230. return this._weight;
  49231. },
  49232. set: function (value) {
  49233. if (value === -1) {
  49234. this._weight = -1;
  49235. return;
  49236. }
  49237. // Else weight must be in [0, 1] range
  49238. this._weight = Math.min(Math.max(value, 0), 1.0);
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. Object.defineProperty(Animatable.prototype, "speedRatio", {
  49244. /**
  49245. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  49246. */
  49247. get: function () {
  49248. return this._speedRatio;
  49249. },
  49250. set: function (value) {
  49251. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  49252. var animation = this._runtimeAnimations[index];
  49253. animation._prepareForSpeedRatioChange(value);
  49254. }
  49255. this._speedRatio = value;
  49256. },
  49257. enumerable: true,
  49258. configurable: true
  49259. });
  49260. // Methods
  49261. /**
  49262. * Synchronize and normalize current Animatable with a source Animatable.
  49263. * This is useful when using animation weights and when animations are not of the same length
  49264. * @param root defines the root Animatable to synchronize with
  49265. * @returns the current Animatable
  49266. */
  49267. Animatable.prototype.syncWith = function (root) {
  49268. this._syncRoot = root;
  49269. if (root) {
  49270. // Make sure this animatable will animate after the root
  49271. var index = this._scene._activeAnimatables.indexOf(this);
  49272. if (index > -1) {
  49273. this._scene._activeAnimatables.splice(index, 1);
  49274. this._scene._activeAnimatables.push(this);
  49275. }
  49276. }
  49277. return this;
  49278. };
  49279. Animatable.prototype.getAnimations = function () {
  49280. return this._runtimeAnimations;
  49281. };
  49282. Animatable.prototype.appendAnimations = function (target, animations) {
  49283. for (var index = 0; index < animations.length; index++) {
  49284. var animation = animations[index];
  49285. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  49286. }
  49287. };
  49288. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  49289. var runtimeAnimations = this._runtimeAnimations;
  49290. for (var index = 0; index < runtimeAnimations.length; index++) {
  49291. if (runtimeAnimations[index].animation.targetProperty === property) {
  49292. return runtimeAnimations[index].animation;
  49293. }
  49294. }
  49295. return null;
  49296. };
  49297. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  49298. var runtimeAnimations = this._runtimeAnimations;
  49299. for (var index = 0; index < runtimeAnimations.length; index++) {
  49300. if (runtimeAnimations[index].animation.targetProperty === property) {
  49301. return runtimeAnimations[index];
  49302. }
  49303. }
  49304. return null;
  49305. };
  49306. Animatable.prototype.reset = function () {
  49307. var runtimeAnimations = this._runtimeAnimations;
  49308. for (var index = 0; index < runtimeAnimations.length; index++) {
  49309. runtimeAnimations[index].reset();
  49310. }
  49311. // Reset to original value
  49312. for (index = 0; index < runtimeAnimations.length; index++) {
  49313. var animation = runtimeAnimations[index];
  49314. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  49315. }
  49316. this._localDelayOffset = null;
  49317. this._pausedDelay = null;
  49318. };
  49319. Animatable.prototype.enableBlending = function (blendingSpeed) {
  49320. var runtimeAnimations = this._runtimeAnimations;
  49321. for (var index = 0; index < runtimeAnimations.length; index++) {
  49322. runtimeAnimations[index].animation.enableBlending = true;
  49323. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  49324. }
  49325. };
  49326. Animatable.prototype.disableBlending = function () {
  49327. var runtimeAnimations = this._runtimeAnimations;
  49328. for (var index = 0; index < runtimeAnimations.length; index++) {
  49329. runtimeAnimations[index].animation.enableBlending = false;
  49330. }
  49331. };
  49332. Animatable.prototype.goToFrame = function (frame) {
  49333. var runtimeAnimations = this._runtimeAnimations;
  49334. if (runtimeAnimations[0]) {
  49335. var fps = runtimeAnimations[0].animation.framePerSecond;
  49336. var currentFrame = runtimeAnimations[0].currentFrame;
  49337. var adjustTime = frame - currentFrame;
  49338. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  49339. if (this._localDelayOffset === null) {
  49340. this._localDelayOffset = 0;
  49341. }
  49342. this._localDelayOffset -= delay;
  49343. }
  49344. for (var index = 0; index < runtimeAnimations.length; index++) {
  49345. runtimeAnimations[index].goToFrame(frame);
  49346. }
  49347. };
  49348. Animatable.prototype.pause = function () {
  49349. if (this._paused) {
  49350. return;
  49351. }
  49352. this._paused = true;
  49353. };
  49354. Animatable.prototype.restart = function () {
  49355. this._paused = false;
  49356. };
  49357. Animatable.prototype.stop = function (animationName) {
  49358. if (animationName) {
  49359. var idx = this._scene._activeAnimatables.indexOf(this);
  49360. if (idx > -1) {
  49361. var runtimeAnimations = this._runtimeAnimations;
  49362. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  49363. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  49364. continue;
  49365. }
  49366. runtimeAnimations[index].dispose();
  49367. runtimeAnimations.splice(index, 1);
  49368. }
  49369. if (runtimeAnimations.length == 0) {
  49370. this._scene._activeAnimatables.splice(idx, 1);
  49371. if (this.onAnimationEnd) {
  49372. this.onAnimationEnd();
  49373. }
  49374. }
  49375. }
  49376. }
  49377. else {
  49378. var index = this._scene._activeAnimatables.indexOf(this);
  49379. if (index > -1) {
  49380. this._scene._activeAnimatables.splice(index, 1);
  49381. var runtimeAnimations = this._runtimeAnimations;
  49382. for (var index = 0; index < runtimeAnimations.length; index++) {
  49383. runtimeAnimations[index].dispose();
  49384. }
  49385. if (this.onAnimationEnd) {
  49386. this.onAnimationEnd();
  49387. }
  49388. }
  49389. }
  49390. };
  49391. Animatable.prototype._animate = function (delay) {
  49392. if (this._paused) {
  49393. this.animationStarted = false;
  49394. if (this._pausedDelay === null) {
  49395. this._pausedDelay = delay;
  49396. }
  49397. return true;
  49398. }
  49399. if (this._localDelayOffset === null) {
  49400. this._localDelayOffset = delay;
  49401. this._pausedDelay = null;
  49402. }
  49403. else if (this._pausedDelay !== null) {
  49404. this._localDelayOffset += delay - this._pausedDelay;
  49405. this._pausedDelay = null;
  49406. }
  49407. if (this._weight === 0) {
  49408. return true;
  49409. }
  49410. // Animating
  49411. var running = false;
  49412. var runtimeAnimations = this._runtimeAnimations;
  49413. var index;
  49414. for (index = 0; index < runtimeAnimations.length; index++) {
  49415. var animation = runtimeAnimations[index];
  49416. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  49417. running = running || isRunning;
  49418. }
  49419. this.animationStarted = running;
  49420. if (!running) {
  49421. // Remove from active animatables
  49422. index = this._scene._activeAnimatables.indexOf(this);
  49423. this._scene._activeAnimatables.splice(index, 1);
  49424. // Dispose all runtime animations
  49425. for (index = 0; index < runtimeAnimations.length; index++) {
  49426. runtimeAnimations[index].dispose();
  49427. }
  49428. }
  49429. if (!running && this.onAnimationEnd) {
  49430. this.onAnimationEnd();
  49431. this.onAnimationEnd = null;
  49432. }
  49433. return running;
  49434. };
  49435. return Animatable;
  49436. }());
  49437. BABYLON.Animatable = Animatable;
  49438. })(BABYLON || (BABYLON = {}));
  49439. //# sourceMappingURL=babylon.animatable.js.map
  49440. "use strict";
  49441. var BABYLON;
  49442. (function (BABYLON) {
  49443. var EasingFunction = /** @class */ (function () {
  49444. function EasingFunction() {
  49445. // Properties
  49446. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  49447. }
  49448. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  49449. get: function () {
  49450. return EasingFunction._EASINGMODE_EASEIN;
  49451. },
  49452. enumerable: true,
  49453. configurable: true
  49454. });
  49455. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  49456. get: function () {
  49457. return EasingFunction._EASINGMODE_EASEOUT;
  49458. },
  49459. enumerable: true,
  49460. configurable: true
  49461. });
  49462. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  49463. get: function () {
  49464. return EasingFunction._EASINGMODE_EASEINOUT;
  49465. },
  49466. enumerable: true,
  49467. configurable: true
  49468. });
  49469. EasingFunction.prototype.setEasingMode = function (easingMode) {
  49470. var n = Math.min(Math.max(easingMode, 0), 2);
  49471. this._easingMode = n;
  49472. };
  49473. EasingFunction.prototype.getEasingMode = function () {
  49474. return this._easingMode;
  49475. };
  49476. EasingFunction.prototype.easeInCore = function (gradient) {
  49477. throw new Error('You must implement this method');
  49478. };
  49479. EasingFunction.prototype.ease = function (gradient) {
  49480. switch (this._easingMode) {
  49481. case EasingFunction.EASINGMODE_EASEIN:
  49482. return this.easeInCore(gradient);
  49483. case EasingFunction.EASINGMODE_EASEOUT:
  49484. return (1 - this.easeInCore(1 - gradient));
  49485. }
  49486. if (gradient >= 0.5) {
  49487. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  49488. }
  49489. return (this.easeInCore(gradient * 2) * 0.5);
  49490. };
  49491. //Statics
  49492. EasingFunction._EASINGMODE_EASEIN = 0;
  49493. EasingFunction._EASINGMODE_EASEOUT = 1;
  49494. EasingFunction._EASINGMODE_EASEINOUT = 2;
  49495. return EasingFunction;
  49496. }());
  49497. BABYLON.EasingFunction = EasingFunction;
  49498. var CircleEase = /** @class */ (function (_super) {
  49499. __extends(CircleEase, _super);
  49500. function CircleEase() {
  49501. return _super !== null && _super.apply(this, arguments) || this;
  49502. }
  49503. CircleEase.prototype.easeInCore = function (gradient) {
  49504. gradient = Math.max(0, Math.min(1, gradient));
  49505. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  49506. };
  49507. return CircleEase;
  49508. }(EasingFunction));
  49509. BABYLON.CircleEase = CircleEase;
  49510. var BackEase = /** @class */ (function (_super) {
  49511. __extends(BackEase, _super);
  49512. function BackEase(amplitude) {
  49513. if (amplitude === void 0) { amplitude = 1; }
  49514. var _this = _super.call(this) || this;
  49515. _this.amplitude = amplitude;
  49516. return _this;
  49517. }
  49518. BackEase.prototype.easeInCore = function (gradient) {
  49519. var num = Math.max(0, this.amplitude);
  49520. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  49521. };
  49522. return BackEase;
  49523. }(EasingFunction));
  49524. BABYLON.BackEase = BackEase;
  49525. var BounceEase = /** @class */ (function (_super) {
  49526. __extends(BounceEase, _super);
  49527. function BounceEase(bounces, bounciness) {
  49528. if (bounces === void 0) { bounces = 3; }
  49529. if (bounciness === void 0) { bounciness = 2; }
  49530. var _this = _super.call(this) || this;
  49531. _this.bounces = bounces;
  49532. _this.bounciness = bounciness;
  49533. return _this;
  49534. }
  49535. BounceEase.prototype.easeInCore = function (gradient) {
  49536. var y = Math.max(0.0, this.bounces);
  49537. var bounciness = this.bounciness;
  49538. if (bounciness <= 1.0) {
  49539. bounciness = 1.001;
  49540. }
  49541. var num9 = Math.pow(bounciness, y);
  49542. var num5 = 1.0 - bounciness;
  49543. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  49544. var num15 = gradient * num4;
  49545. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  49546. var num3 = Math.floor(num65);
  49547. var num13 = num3 + 1.0;
  49548. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  49549. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  49550. var num7 = (num8 + num12) * 0.5;
  49551. var num6 = gradient - num7;
  49552. var num2 = num7 - num8;
  49553. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  49554. };
  49555. return BounceEase;
  49556. }(EasingFunction));
  49557. BABYLON.BounceEase = BounceEase;
  49558. var CubicEase = /** @class */ (function (_super) {
  49559. __extends(CubicEase, _super);
  49560. function CubicEase() {
  49561. return _super !== null && _super.apply(this, arguments) || this;
  49562. }
  49563. CubicEase.prototype.easeInCore = function (gradient) {
  49564. return (gradient * gradient * gradient);
  49565. };
  49566. return CubicEase;
  49567. }(EasingFunction));
  49568. BABYLON.CubicEase = CubicEase;
  49569. var ElasticEase = /** @class */ (function (_super) {
  49570. __extends(ElasticEase, _super);
  49571. function ElasticEase(oscillations, springiness) {
  49572. if (oscillations === void 0) { oscillations = 3; }
  49573. if (springiness === void 0) { springiness = 3; }
  49574. var _this = _super.call(this) || this;
  49575. _this.oscillations = oscillations;
  49576. _this.springiness = springiness;
  49577. return _this;
  49578. }
  49579. ElasticEase.prototype.easeInCore = function (gradient) {
  49580. var num2;
  49581. var num3 = Math.max(0.0, this.oscillations);
  49582. var num = Math.max(0.0, this.springiness);
  49583. if (num == 0) {
  49584. num2 = gradient;
  49585. }
  49586. else {
  49587. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  49588. }
  49589. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  49590. };
  49591. return ElasticEase;
  49592. }(EasingFunction));
  49593. BABYLON.ElasticEase = ElasticEase;
  49594. var ExponentialEase = /** @class */ (function (_super) {
  49595. __extends(ExponentialEase, _super);
  49596. function ExponentialEase(exponent) {
  49597. if (exponent === void 0) { exponent = 2; }
  49598. var _this = _super.call(this) || this;
  49599. _this.exponent = exponent;
  49600. return _this;
  49601. }
  49602. ExponentialEase.prototype.easeInCore = function (gradient) {
  49603. if (this.exponent <= 0) {
  49604. return gradient;
  49605. }
  49606. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  49607. };
  49608. return ExponentialEase;
  49609. }(EasingFunction));
  49610. BABYLON.ExponentialEase = ExponentialEase;
  49611. var PowerEase = /** @class */ (function (_super) {
  49612. __extends(PowerEase, _super);
  49613. function PowerEase(power) {
  49614. if (power === void 0) { power = 2; }
  49615. var _this = _super.call(this) || this;
  49616. _this.power = power;
  49617. return _this;
  49618. }
  49619. PowerEase.prototype.easeInCore = function (gradient) {
  49620. var y = Math.max(0.0, this.power);
  49621. return Math.pow(gradient, y);
  49622. };
  49623. return PowerEase;
  49624. }(EasingFunction));
  49625. BABYLON.PowerEase = PowerEase;
  49626. var QuadraticEase = /** @class */ (function (_super) {
  49627. __extends(QuadraticEase, _super);
  49628. function QuadraticEase() {
  49629. return _super !== null && _super.apply(this, arguments) || this;
  49630. }
  49631. QuadraticEase.prototype.easeInCore = function (gradient) {
  49632. return (gradient * gradient);
  49633. };
  49634. return QuadraticEase;
  49635. }(EasingFunction));
  49636. BABYLON.QuadraticEase = QuadraticEase;
  49637. var QuarticEase = /** @class */ (function (_super) {
  49638. __extends(QuarticEase, _super);
  49639. function QuarticEase() {
  49640. return _super !== null && _super.apply(this, arguments) || this;
  49641. }
  49642. QuarticEase.prototype.easeInCore = function (gradient) {
  49643. return (gradient * gradient * gradient * gradient);
  49644. };
  49645. return QuarticEase;
  49646. }(EasingFunction));
  49647. BABYLON.QuarticEase = QuarticEase;
  49648. var QuinticEase = /** @class */ (function (_super) {
  49649. __extends(QuinticEase, _super);
  49650. function QuinticEase() {
  49651. return _super !== null && _super.apply(this, arguments) || this;
  49652. }
  49653. QuinticEase.prototype.easeInCore = function (gradient) {
  49654. return (gradient * gradient * gradient * gradient * gradient);
  49655. };
  49656. return QuinticEase;
  49657. }(EasingFunction));
  49658. BABYLON.QuinticEase = QuinticEase;
  49659. var SineEase = /** @class */ (function (_super) {
  49660. __extends(SineEase, _super);
  49661. function SineEase() {
  49662. return _super !== null && _super.apply(this, arguments) || this;
  49663. }
  49664. SineEase.prototype.easeInCore = function (gradient) {
  49665. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  49666. };
  49667. return SineEase;
  49668. }(EasingFunction));
  49669. BABYLON.SineEase = SineEase;
  49670. var BezierCurveEase = /** @class */ (function (_super) {
  49671. __extends(BezierCurveEase, _super);
  49672. function BezierCurveEase(x1, y1, x2, y2) {
  49673. if (x1 === void 0) { x1 = 0; }
  49674. if (y1 === void 0) { y1 = 0; }
  49675. if (x2 === void 0) { x2 = 1; }
  49676. if (y2 === void 0) { y2 = 1; }
  49677. var _this = _super.call(this) || this;
  49678. _this.x1 = x1;
  49679. _this.y1 = y1;
  49680. _this.x2 = x2;
  49681. _this.y2 = y2;
  49682. return _this;
  49683. }
  49684. BezierCurveEase.prototype.easeInCore = function (gradient) {
  49685. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  49686. };
  49687. return BezierCurveEase;
  49688. }(EasingFunction));
  49689. BABYLON.BezierCurveEase = BezierCurveEase;
  49690. })(BABYLON || (BABYLON = {}));
  49691. //# sourceMappingURL=babylon.easing.js.map
  49692. "use strict";
  49693. var BABYLON;
  49694. (function (BABYLON) {
  49695. /**
  49696. * A Condition applied to an Action
  49697. */
  49698. var Condition = /** @class */ (function () {
  49699. /**
  49700. * Creates a new Condition
  49701. * @param actionManager the manager of the action the condition is applied to
  49702. */
  49703. function Condition(actionManager) {
  49704. this._actionManager = actionManager;
  49705. }
  49706. /**
  49707. * Check if the current condition is valid
  49708. * @returns a boolean
  49709. */
  49710. Condition.prototype.isValid = function () {
  49711. return true;
  49712. };
  49713. /**
  49714. * Internal only
  49715. * @ignore
  49716. */
  49717. Condition.prototype._getProperty = function (propertyPath) {
  49718. return this._actionManager._getProperty(propertyPath);
  49719. };
  49720. /**
  49721. * Internal only
  49722. * @ignore
  49723. */
  49724. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  49725. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49726. };
  49727. /**
  49728. * Serialize placeholder for child classes
  49729. * @returns the serialized object
  49730. */
  49731. Condition.prototype.serialize = function () {
  49732. };
  49733. /**
  49734. * Internal only
  49735. * @ignore
  49736. */
  49737. Condition.prototype._serialize = function (serializedCondition) {
  49738. return {
  49739. type: 2,
  49740. children: [],
  49741. name: serializedCondition.name,
  49742. properties: serializedCondition.properties
  49743. };
  49744. };
  49745. return Condition;
  49746. }());
  49747. BABYLON.Condition = Condition;
  49748. /**
  49749. * Defines specific conditional operators as extensions of Condition
  49750. */
  49751. var ValueCondition = /** @class */ (function (_super) {
  49752. __extends(ValueCondition, _super);
  49753. /**
  49754. * Creates a new ValueCondition
  49755. * @param actionManager manager for the action the condition applies to
  49756. * @param target for the action
  49757. * @param propertyPath path to specify the property of the target the conditional operator uses
  49758. * @param value the vale compared by the conditional operator against the current value of the property
  49759. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  49760. */
  49761. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  49762. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  49763. var _this = _super.call(this, actionManager) || this;
  49764. _this.propertyPath = propertyPath;
  49765. _this.value = value;
  49766. _this.operator = operator;
  49767. _this._target = target;
  49768. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  49769. _this._property = _this._getProperty(_this.propertyPath);
  49770. return _this;
  49771. }
  49772. Object.defineProperty(ValueCondition, "IsEqual", {
  49773. /**
  49774. * returns the number for IsEqual
  49775. */
  49776. get: function () {
  49777. return ValueCondition._IsEqual;
  49778. },
  49779. enumerable: true,
  49780. configurable: true
  49781. });
  49782. Object.defineProperty(ValueCondition, "IsDifferent", {
  49783. /**
  49784. * Returns the number for IsDifferent
  49785. */
  49786. get: function () {
  49787. return ValueCondition._IsDifferent;
  49788. },
  49789. enumerable: true,
  49790. configurable: true
  49791. });
  49792. Object.defineProperty(ValueCondition, "IsGreater", {
  49793. /**
  49794. * Returns the number for IsGreater
  49795. */
  49796. get: function () {
  49797. return ValueCondition._IsGreater;
  49798. },
  49799. enumerable: true,
  49800. configurable: true
  49801. });
  49802. Object.defineProperty(ValueCondition, "IsLesser", {
  49803. /**
  49804. * Returns the number for IsLesser
  49805. */
  49806. get: function () {
  49807. return ValueCondition._IsLesser;
  49808. },
  49809. enumerable: true,
  49810. configurable: true
  49811. });
  49812. /**
  49813. * Compares the given value with the property value for the specified conditional operator
  49814. * @returns the result of the comparison
  49815. */
  49816. ValueCondition.prototype.isValid = function () {
  49817. switch (this.operator) {
  49818. case ValueCondition.IsGreater:
  49819. return this._effectiveTarget[this._property] > this.value;
  49820. case ValueCondition.IsLesser:
  49821. return this._effectiveTarget[this._property] < this.value;
  49822. case ValueCondition.IsEqual:
  49823. case ValueCondition.IsDifferent:
  49824. var check;
  49825. if (this.value.equals) {
  49826. check = this.value.equals(this._effectiveTarget[this._property]);
  49827. }
  49828. else {
  49829. check = this.value === this._effectiveTarget[this._property];
  49830. }
  49831. return this.operator === ValueCondition.IsEqual ? check : !check;
  49832. }
  49833. return false;
  49834. };
  49835. /**
  49836. * Serialize the ValueCondition into a JSON compatible object
  49837. * @returns serialization object
  49838. */
  49839. ValueCondition.prototype.serialize = function () {
  49840. return this._serialize({
  49841. name: "ValueCondition",
  49842. properties: [
  49843. BABYLON.Action._GetTargetProperty(this._target),
  49844. { name: "propertyPath", value: this.propertyPath },
  49845. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49846. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  49847. ]
  49848. });
  49849. };
  49850. /**
  49851. * Gets the name of the conditional operator for the ValueCondition
  49852. * @param operator the conditional operator
  49853. * @returns the name
  49854. */
  49855. ValueCondition.GetOperatorName = function (operator) {
  49856. switch (operator) {
  49857. case ValueCondition._IsEqual: return "IsEqual";
  49858. case ValueCondition._IsDifferent: return "IsDifferent";
  49859. case ValueCondition._IsGreater: return "IsGreater";
  49860. case ValueCondition._IsLesser: return "IsLesser";
  49861. default: return "";
  49862. }
  49863. };
  49864. /**
  49865. * Internal only
  49866. * @ignore
  49867. */
  49868. ValueCondition._IsEqual = 0;
  49869. /**
  49870. * Internal only
  49871. * @ignore
  49872. */
  49873. ValueCondition._IsDifferent = 1;
  49874. /**
  49875. * Internal only
  49876. * @ignore
  49877. */
  49878. ValueCondition._IsGreater = 2;
  49879. /**
  49880. * Internal only
  49881. * @ignore
  49882. */
  49883. ValueCondition._IsLesser = 3;
  49884. return ValueCondition;
  49885. }(Condition));
  49886. BABYLON.ValueCondition = ValueCondition;
  49887. /**
  49888. * Defines a predicate condition as an extension of Condition
  49889. */
  49890. var PredicateCondition = /** @class */ (function (_super) {
  49891. __extends(PredicateCondition, _super);
  49892. /**
  49893. * Creates a new {BABYLON.PredicateCondition}
  49894. * @param actionManager manager for the action the condition applies to
  49895. * @param predicate
  49896. */
  49897. function PredicateCondition(actionManager, predicate) {
  49898. var _this = _super.call(this, actionManager) || this;
  49899. _this.predicate = predicate;
  49900. return _this;
  49901. }
  49902. /**
  49903. * @returns the validity of the predicate condition
  49904. */
  49905. PredicateCondition.prototype.isValid = function () {
  49906. return this.predicate();
  49907. };
  49908. return PredicateCondition;
  49909. }(Condition));
  49910. BABYLON.PredicateCondition = PredicateCondition;
  49911. /**
  49912. * Defines a state condition as an extension of {BABYLON.Condition}
  49913. */
  49914. var StateCondition = /** @class */ (function (_super) {
  49915. __extends(StateCondition, _super);
  49916. /**
  49917. * Creates a new {BABYLON.StateCondition}
  49918. * @param actionManager manager for the action the condition applies to
  49919. * @param target of the condition
  49920. * @param value to compare with target state
  49921. */
  49922. function StateCondition(actionManager, target, value) {
  49923. var _this = _super.call(this, actionManager) || this;
  49924. _this.value = value;
  49925. _this._target = target;
  49926. return _this;
  49927. }
  49928. /**
  49929. * @returns the validity of the state
  49930. */
  49931. StateCondition.prototype.isValid = function () {
  49932. return this._target.state === this.value;
  49933. };
  49934. /**
  49935. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  49936. * @returns serialization object
  49937. */
  49938. StateCondition.prototype.serialize = function () {
  49939. return this._serialize({
  49940. name: "StateCondition",
  49941. properties: [
  49942. BABYLON.Action._GetTargetProperty(this._target),
  49943. { name: "value", value: this.value }
  49944. ]
  49945. });
  49946. };
  49947. return StateCondition;
  49948. }(Condition));
  49949. BABYLON.StateCondition = StateCondition;
  49950. })(BABYLON || (BABYLON = {}));
  49951. //# sourceMappingURL=babylon.condition.js.map
  49952. "use strict";
  49953. var BABYLON;
  49954. (function (BABYLON) {
  49955. /**
  49956. * The action to be carried out following a trigger
  49957. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  49958. */
  49959. var Action = /** @class */ (function () {
  49960. /**
  49961. * Creates a new Action
  49962. * @param triggerOptions the trigger, with or without parameters, for the action
  49963. * @param condition an optional determinant of action
  49964. */
  49965. function Action(triggerOptions, condition) {
  49966. this.triggerOptions = triggerOptions;
  49967. /**
  49968. * An event triggered prior to action being executed.
  49969. */
  49970. this.onBeforeExecuteObservable = new BABYLON.Observable();
  49971. if (triggerOptions.parameter) {
  49972. this.trigger = triggerOptions.trigger;
  49973. this._triggerParameter = triggerOptions.parameter;
  49974. }
  49975. else {
  49976. this.trigger = triggerOptions;
  49977. }
  49978. this._nextActiveAction = this;
  49979. this._condition = condition;
  49980. }
  49981. /**
  49982. * Internal only
  49983. * @ignore
  49984. */
  49985. Action.prototype._prepare = function () {
  49986. };
  49987. /**
  49988. * Gets the trigger parameters
  49989. * @returns the trigger parameters
  49990. */
  49991. Action.prototype.getTriggerParameter = function () {
  49992. return this._triggerParameter;
  49993. };
  49994. /**
  49995. * Internal only - executes current action event
  49996. * @ignore
  49997. */
  49998. Action.prototype._executeCurrent = function (evt) {
  49999. if (this._nextActiveAction._condition) {
  50000. var condition = this._nextActiveAction._condition;
  50001. var currentRenderId = this._actionManager.getScene().getRenderId();
  50002. // We cache the current evaluation for the current frame
  50003. if (condition._evaluationId === currentRenderId) {
  50004. if (!condition._currentResult) {
  50005. return;
  50006. }
  50007. }
  50008. else {
  50009. condition._evaluationId = currentRenderId;
  50010. if (!condition.isValid()) {
  50011. condition._currentResult = false;
  50012. return;
  50013. }
  50014. condition._currentResult = true;
  50015. }
  50016. }
  50017. this.onBeforeExecuteObservable.notifyObservers(this);
  50018. this._nextActiveAction.execute(evt);
  50019. this.skipToNextActiveAction();
  50020. };
  50021. /**
  50022. * Execute placeholder for child classes
  50023. * @param evt optional action event
  50024. */
  50025. Action.prototype.execute = function (evt) {
  50026. };
  50027. /**
  50028. * Skips to next active action
  50029. */
  50030. Action.prototype.skipToNextActiveAction = function () {
  50031. if (this._nextActiveAction._child) {
  50032. if (!this._nextActiveAction._child._actionManager) {
  50033. this._nextActiveAction._child._actionManager = this._actionManager;
  50034. }
  50035. this._nextActiveAction = this._nextActiveAction._child;
  50036. }
  50037. else {
  50038. this._nextActiveAction = this;
  50039. }
  50040. };
  50041. /**
  50042. * Adds action to chain of actions, may be a DoNothingAction
  50043. * @param index The index of the attribute.
  50044. * @returns The action passed in
  50045. * @see https://www.babylonjs-playground.com/#1T30HR#0
  50046. */
  50047. Action.prototype.then = function (action) {
  50048. this._child = action;
  50049. action._actionManager = this._actionManager;
  50050. action._prepare();
  50051. return action;
  50052. };
  50053. /**
  50054. * Internal only
  50055. * @ignore
  50056. */
  50057. Action.prototype._getProperty = function (propertyPath) {
  50058. return this._actionManager._getProperty(propertyPath);
  50059. };
  50060. /**
  50061. * Internal only
  50062. * @ignore
  50063. */
  50064. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  50065. return this._actionManager._getEffectiveTarget(target, propertyPath);
  50066. };
  50067. /**
  50068. * Serialize placeholder for child classes
  50069. * @param parent of child
  50070. * @returns the serialized object
  50071. */
  50072. Action.prototype.serialize = function (parent) {
  50073. };
  50074. /**
  50075. * Internal only called by serialize
  50076. * @ignore
  50077. */
  50078. Action.prototype._serialize = function (serializedAction, parent) {
  50079. var serializationObject = {
  50080. type: 1,
  50081. children: [],
  50082. name: serializedAction.name,
  50083. properties: serializedAction.properties || []
  50084. };
  50085. // Serialize child
  50086. if (this._child) {
  50087. this._child.serialize(serializationObject);
  50088. }
  50089. // Check if "this" has a condition
  50090. if (this._condition) {
  50091. var serializedCondition = this._condition.serialize();
  50092. serializedCondition.children.push(serializationObject);
  50093. if (parent) {
  50094. parent.children.push(serializedCondition);
  50095. }
  50096. return serializedCondition;
  50097. }
  50098. if (parent) {
  50099. parent.children.push(serializationObject);
  50100. }
  50101. return serializationObject;
  50102. };
  50103. /**
  50104. * Internal only
  50105. * @ignore
  50106. */
  50107. Action._SerializeValueAsString = function (value) {
  50108. if (typeof value === "number") {
  50109. return value.toString();
  50110. }
  50111. if (typeof value === "boolean") {
  50112. return value ? "true" : "false";
  50113. }
  50114. if (value instanceof BABYLON.Vector2) {
  50115. return value.x + ", " + value.y;
  50116. }
  50117. if (value instanceof BABYLON.Vector3) {
  50118. return value.x + ", " + value.y + ", " + value.z;
  50119. }
  50120. if (value instanceof BABYLON.Color3) {
  50121. return value.r + ", " + value.g + ", " + value.b;
  50122. }
  50123. if (value instanceof BABYLON.Color4) {
  50124. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  50125. }
  50126. return value; // string
  50127. };
  50128. /**
  50129. * Internal only
  50130. * @ignore
  50131. */
  50132. Action._GetTargetProperty = function (target) {
  50133. return {
  50134. name: "target",
  50135. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  50136. : target instanceof BABYLON.Light ? "LightProperties"
  50137. : target instanceof BABYLON.Camera ? "CameraProperties"
  50138. : "SceneProperties",
  50139. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  50140. };
  50141. };
  50142. return Action;
  50143. }());
  50144. BABYLON.Action = Action;
  50145. })(BABYLON || (BABYLON = {}));
  50146. //# sourceMappingURL=babylon.action.js.map
  50147. "use strict";
  50148. var BABYLON;
  50149. (function (BABYLON) {
  50150. /**
  50151. * ActionEvent is the event being sent when an action is triggered.
  50152. */
  50153. var ActionEvent = /** @class */ (function () {
  50154. /**
  50155. * @param source The mesh or sprite that triggered the action.
  50156. * @param pointerX The X mouse cursor position at the time of the event
  50157. * @param pointerY The Y mouse cursor position at the time of the event
  50158. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  50159. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  50160. */
  50161. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  50162. this.source = source;
  50163. this.pointerX = pointerX;
  50164. this.pointerY = pointerY;
  50165. this.meshUnderPointer = meshUnderPointer;
  50166. this.sourceEvent = sourceEvent;
  50167. this.additionalData = additionalData;
  50168. }
  50169. /**
  50170. * Helper function to auto-create an ActionEvent from a source mesh.
  50171. * @param source The source mesh that triggered the event
  50172. * @param evt {Event} The original (browser) event
  50173. */
  50174. ActionEvent.CreateNew = function (source, evt, additionalData) {
  50175. var scene = source.getScene();
  50176. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  50177. };
  50178. /**
  50179. * Helper function to auto-create an ActionEvent from a source mesh.
  50180. * @param source The source sprite that triggered the event
  50181. * @param scene Scene associated with the sprite
  50182. * @param evt {Event} The original (browser) event
  50183. */
  50184. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  50185. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  50186. };
  50187. /**
  50188. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  50189. * @param scene the scene where the event occurred
  50190. * @param evt {Event} The original (browser) event
  50191. */
  50192. ActionEvent.CreateNewFromScene = function (scene, evt) {
  50193. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  50194. };
  50195. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  50196. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  50197. };
  50198. return ActionEvent;
  50199. }());
  50200. BABYLON.ActionEvent = ActionEvent;
  50201. /**
  50202. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  50203. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  50204. */
  50205. var ActionManager = /** @class */ (function () {
  50206. function ActionManager(scene) {
  50207. // Members
  50208. this.actions = new Array();
  50209. this.hoverCursor = '';
  50210. this._scene = scene;
  50211. scene._actionManagers.push(this);
  50212. }
  50213. Object.defineProperty(ActionManager, "NothingTrigger", {
  50214. get: function () {
  50215. return ActionManager._NothingTrigger;
  50216. },
  50217. enumerable: true,
  50218. configurable: true
  50219. });
  50220. Object.defineProperty(ActionManager, "OnPickTrigger", {
  50221. get: function () {
  50222. return ActionManager._OnPickTrigger;
  50223. },
  50224. enumerable: true,
  50225. configurable: true
  50226. });
  50227. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  50228. get: function () {
  50229. return ActionManager._OnLeftPickTrigger;
  50230. },
  50231. enumerable: true,
  50232. configurable: true
  50233. });
  50234. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  50235. get: function () {
  50236. return ActionManager._OnRightPickTrigger;
  50237. },
  50238. enumerable: true,
  50239. configurable: true
  50240. });
  50241. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  50242. get: function () {
  50243. return ActionManager._OnCenterPickTrigger;
  50244. },
  50245. enumerable: true,
  50246. configurable: true
  50247. });
  50248. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  50249. get: function () {
  50250. return ActionManager._OnPickDownTrigger;
  50251. },
  50252. enumerable: true,
  50253. configurable: true
  50254. });
  50255. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  50256. get: function () {
  50257. return ActionManager._OnDoublePickTrigger;
  50258. },
  50259. enumerable: true,
  50260. configurable: true
  50261. });
  50262. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  50263. get: function () {
  50264. return ActionManager._OnPickUpTrigger;
  50265. },
  50266. enumerable: true,
  50267. configurable: true
  50268. });
  50269. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  50270. /// This trigger will only be raised if you also declared a OnPickDown
  50271. get: function () {
  50272. return ActionManager._OnPickOutTrigger;
  50273. },
  50274. enumerable: true,
  50275. configurable: true
  50276. });
  50277. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  50278. get: function () {
  50279. return ActionManager._OnLongPressTrigger;
  50280. },
  50281. enumerable: true,
  50282. configurable: true
  50283. });
  50284. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  50285. get: function () {
  50286. return ActionManager._OnPointerOverTrigger;
  50287. },
  50288. enumerable: true,
  50289. configurable: true
  50290. });
  50291. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  50292. get: function () {
  50293. return ActionManager._OnPointerOutTrigger;
  50294. },
  50295. enumerable: true,
  50296. configurable: true
  50297. });
  50298. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  50299. get: function () {
  50300. return ActionManager._OnEveryFrameTrigger;
  50301. },
  50302. enumerable: true,
  50303. configurable: true
  50304. });
  50305. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  50306. get: function () {
  50307. return ActionManager._OnIntersectionEnterTrigger;
  50308. },
  50309. enumerable: true,
  50310. configurable: true
  50311. });
  50312. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  50313. get: function () {
  50314. return ActionManager._OnIntersectionExitTrigger;
  50315. },
  50316. enumerable: true,
  50317. configurable: true
  50318. });
  50319. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  50320. get: function () {
  50321. return ActionManager._OnKeyDownTrigger;
  50322. },
  50323. enumerable: true,
  50324. configurable: true
  50325. });
  50326. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  50327. get: function () {
  50328. return ActionManager._OnKeyUpTrigger;
  50329. },
  50330. enumerable: true,
  50331. configurable: true
  50332. });
  50333. // Methods
  50334. ActionManager.prototype.dispose = function () {
  50335. var index = this._scene._actionManagers.indexOf(this);
  50336. for (var i = 0; i < this.actions.length; i++) {
  50337. var action = this.actions[i];
  50338. ActionManager.Triggers[action.trigger]--;
  50339. if (ActionManager.Triggers[action.trigger] === 0) {
  50340. delete ActionManager.Triggers[action.trigger];
  50341. }
  50342. }
  50343. if (index > -1) {
  50344. this._scene._actionManagers.splice(index, 1);
  50345. }
  50346. };
  50347. ActionManager.prototype.getScene = function () {
  50348. return this._scene;
  50349. };
  50350. /**
  50351. * Does this action manager handles actions of any of the given triggers
  50352. * @param {number[]} triggers - the triggers to be tested
  50353. * @return {boolean} whether one (or more) of the triggers is handeled
  50354. */
  50355. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  50356. for (var index = 0; index < this.actions.length; index++) {
  50357. var action = this.actions[index];
  50358. if (triggers.indexOf(action.trigger) > -1) {
  50359. return true;
  50360. }
  50361. }
  50362. return false;
  50363. };
  50364. /**
  50365. * Does this action manager handles actions of a given trigger
  50366. * @param {number} trigger - the trigger to be tested
  50367. * @return {boolean} whether the trigger is handeled
  50368. */
  50369. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  50370. for (var index = 0; index < this.actions.length; index++) {
  50371. var action = this.actions[index];
  50372. if (action.trigger === trigger) {
  50373. return true;
  50374. }
  50375. }
  50376. return false;
  50377. };
  50378. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  50379. /**
  50380. * Does this action manager has pointer triggers
  50381. * @return {boolean} whether or not it has pointer triggers
  50382. */
  50383. get: function () {
  50384. for (var index = 0; index < this.actions.length; index++) {
  50385. var action = this.actions[index];
  50386. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  50387. return true;
  50388. }
  50389. }
  50390. return false;
  50391. },
  50392. enumerable: true,
  50393. configurable: true
  50394. });
  50395. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  50396. /**
  50397. * Does this action manager has pick triggers
  50398. * @return {boolean} whether or not it has pick triggers
  50399. */
  50400. get: function () {
  50401. for (var index = 0; index < this.actions.length; index++) {
  50402. var action = this.actions[index];
  50403. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  50404. return true;
  50405. }
  50406. }
  50407. return false;
  50408. },
  50409. enumerable: true,
  50410. configurable: true
  50411. });
  50412. Object.defineProperty(ActionManager, "HasTriggers", {
  50413. /**
  50414. * Does exist one action manager with at least one trigger
  50415. * @return {boolean} whether or not it exists one action manager with one trigger
  50416. **/
  50417. get: function () {
  50418. for (var t in ActionManager.Triggers) {
  50419. if (ActionManager.Triggers.hasOwnProperty(t)) {
  50420. return true;
  50421. }
  50422. }
  50423. return false;
  50424. },
  50425. enumerable: true,
  50426. configurable: true
  50427. });
  50428. Object.defineProperty(ActionManager, "HasPickTriggers", {
  50429. /**
  50430. * Does exist one action manager with at least one pick trigger
  50431. * @return {boolean} whether or not it exists one action manager with one pick trigger
  50432. **/
  50433. get: function () {
  50434. for (var t in ActionManager.Triggers) {
  50435. if (ActionManager.Triggers.hasOwnProperty(t)) {
  50436. var t_int = parseInt(t);
  50437. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  50438. return true;
  50439. }
  50440. }
  50441. }
  50442. return false;
  50443. },
  50444. enumerable: true,
  50445. configurable: true
  50446. });
  50447. /**
  50448. * Does exist one action manager that handles actions of a given trigger
  50449. * @param {number} trigger - the trigger to be tested
  50450. * @return {boolean} whether the trigger is handeled by at least one action manager
  50451. **/
  50452. ActionManager.HasSpecificTrigger = function (trigger) {
  50453. for (var t in ActionManager.Triggers) {
  50454. if (ActionManager.Triggers.hasOwnProperty(t)) {
  50455. var t_int = parseInt(t);
  50456. if (t_int === trigger) {
  50457. return true;
  50458. }
  50459. }
  50460. }
  50461. return false;
  50462. };
  50463. /**
  50464. * Registers an action to this action manager
  50465. * @param {BABYLON.Action} action - the action to be registered
  50466. * @return {BABYLON.Action} the action amended (prepared) after registration
  50467. */
  50468. ActionManager.prototype.registerAction = function (action) {
  50469. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  50470. if (this.getScene().actionManager !== this) {
  50471. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  50472. return null;
  50473. }
  50474. }
  50475. this.actions.push(action);
  50476. if (ActionManager.Triggers[action.trigger]) {
  50477. ActionManager.Triggers[action.trigger]++;
  50478. }
  50479. else {
  50480. ActionManager.Triggers[action.trigger] = 1;
  50481. }
  50482. action._actionManager = this;
  50483. action._prepare();
  50484. return action;
  50485. };
  50486. /**
  50487. * Unregisters an action to this action manager
  50488. * @param action The action to be unregistered
  50489. * @return whether the action has been unregistered
  50490. */
  50491. ActionManager.prototype.unregisterAction = function (action) {
  50492. var index = this.actions.indexOf(action);
  50493. if (index !== -1) {
  50494. this.actions.splice(index, 1);
  50495. ActionManager.Triggers[action.trigger] -= 1;
  50496. if (ActionManager.Triggers[action.trigger] === 0) {
  50497. delete ActionManager.Triggers[action.trigger];
  50498. }
  50499. delete action._actionManager;
  50500. return true;
  50501. }
  50502. return false;
  50503. };
  50504. /**
  50505. * Process a specific trigger
  50506. * @param {number} trigger - the trigger to process
  50507. * @param evt {BABYLON.ActionEvent} the event details to be processed
  50508. */
  50509. ActionManager.prototype.processTrigger = function (trigger, evt) {
  50510. for (var index = 0; index < this.actions.length; index++) {
  50511. var action = this.actions[index];
  50512. if (action.trigger === trigger) {
  50513. if (evt) {
  50514. if (trigger === ActionManager.OnKeyUpTrigger
  50515. || trigger === ActionManager.OnKeyDownTrigger) {
  50516. var parameter = action.getTriggerParameter();
  50517. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  50518. if (!parameter.toLowerCase) {
  50519. continue;
  50520. }
  50521. var lowerCase = parameter.toLowerCase();
  50522. if (lowerCase !== evt.sourceEvent.key) {
  50523. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  50524. var actualkey = String.fromCharCode(unicode).toLowerCase();
  50525. if (actualkey !== lowerCase) {
  50526. continue;
  50527. }
  50528. }
  50529. }
  50530. }
  50531. }
  50532. action._executeCurrent(evt);
  50533. }
  50534. }
  50535. };
  50536. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  50537. var properties = propertyPath.split(".");
  50538. for (var index = 0; index < properties.length - 1; index++) {
  50539. target = target[properties[index]];
  50540. }
  50541. return target;
  50542. };
  50543. ActionManager.prototype._getProperty = function (propertyPath) {
  50544. var properties = propertyPath.split(".");
  50545. return properties[properties.length - 1];
  50546. };
  50547. ActionManager.prototype.serialize = function (name) {
  50548. var root = {
  50549. children: new Array(),
  50550. name: name,
  50551. type: 3,
  50552. properties: new Array() // Empty for root but required
  50553. };
  50554. for (var i = 0; i < this.actions.length; i++) {
  50555. var triggerObject = {
  50556. type: 0,
  50557. children: new Array(),
  50558. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  50559. properties: new Array()
  50560. };
  50561. var triggerOptions = this.actions[i].triggerOptions;
  50562. if (triggerOptions && typeof triggerOptions !== "number") {
  50563. if (triggerOptions.parameter instanceof BABYLON.Node) {
  50564. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  50565. }
  50566. else {
  50567. var parameter = {};
  50568. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  50569. if (triggerOptions.parameter.mesh) {
  50570. parameter._meshId = triggerOptions.parameter.mesh.id;
  50571. }
  50572. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  50573. }
  50574. }
  50575. // Serialize child action, recursively
  50576. this.actions[i].serialize(triggerObject);
  50577. // Add serialized trigger
  50578. root.children.push(triggerObject);
  50579. }
  50580. return root;
  50581. };
  50582. ActionManager.Parse = function (parsedActions, object, scene) {
  50583. var actionManager = new ActionManager(scene);
  50584. if (object === null)
  50585. scene.actionManager = actionManager;
  50586. else
  50587. object.actionManager = actionManager;
  50588. // instanciate a new object
  50589. var instanciate = function (name, params) {
  50590. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  50591. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  50592. newInstance.constructor.apply(newInstance, params);
  50593. return newInstance;
  50594. };
  50595. var parseParameter = function (name, value, target, propertyPath) {
  50596. if (propertyPath === null) {
  50597. // String, boolean or float
  50598. var floatValue = parseFloat(value);
  50599. if (value === "true" || value === "false")
  50600. return value === "true";
  50601. else
  50602. return isNaN(floatValue) ? value : floatValue;
  50603. }
  50604. var effectiveTarget = propertyPath.split(".");
  50605. var values = value.split(",");
  50606. // Get effective Target
  50607. for (var i = 0; i < effectiveTarget.length; i++) {
  50608. target = target[effectiveTarget[i]];
  50609. }
  50610. // Return appropriate value with its type
  50611. if (typeof (target) === "boolean")
  50612. return values[0] === "true";
  50613. if (typeof (target) === "string")
  50614. return values[0];
  50615. // Parameters with multiple values such as Vector3 etc.
  50616. var split = new Array();
  50617. for (var i = 0; i < values.length; i++)
  50618. split.push(parseFloat(values[i]));
  50619. if (target instanceof BABYLON.Vector3)
  50620. return BABYLON.Vector3.FromArray(split);
  50621. if (target instanceof BABYLON.Vector4)
  50622. return BABYLON.Vector4.FromArray(split);
  50623. if (target instanceof BABYLON.Color3)
  50624. return BABYLON.Color3.FromArray(split);
  50625. if (target instanceof BABYLON.Color4)
  50626. return BABYLON.Color4.FromArray(split);
  50627. return parseFloat(values[0]);
  50628. };
  50629. // traverse graph per trigger
  50630. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  50631. if (combineArray === void 0) { combineArray = null; }
  50632. if (parsedAction.detached)
  50633. return;
  50634. var parameters = new Array();
  50635. var target = null;
  50636. var propertyPath = null;
  50637. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  50638. // Parameters
  50639. if (parsedAction.type === 2)
  50640. parameters.push(actionManager);
  50641. else
  50642. parameters.push(trigger);
  50643. if (combine) {
  50644. var actions = new Array();
  50645. for (var j = 0; j < parsedAction.combine.length; j++) {
  50646. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  50647. }
  50648. parameters.push(actions);
  50649. }
  50650. else {
  50651. for (var i = 0; i < parsedAction.properties.length; i++) {
  50652. var value = parsedAction.properties[i].value;
  50653. var name = parsedAction.properties[i].name;
  50654. var targetType = parsedAction.properties[i].targetType;
  50655. if (name === "target")
  50656. if (targetType !== null && targetType === "SceneProperties")
  50657. value = target = scene;
  50658. else
  50659. value = target = scene.getNodeByName(value);
  50660. else if (name === "parent")
  50661. value = scene.getNodeByName(value);
  50662. else if (name === "sound")
  50663. value = scene.getSoundByName(value);
  50664. else if (name !== "propertyPath") {
  50665. if (parsedAction.type === 2 && name === "operator")
  50666. value = BABYLON.ValueCondition[value];
  50667. else
  50668. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  50669. }
  50670. else {
  50671. propertyPath = value;
  50672. }
  50673. parameters.push(value);
  50674. }
  50675. }
  50676. if (combineArray === null) {
  50677. parameters.push(condition);
  50678. }
  50679. else {
  50680. parameters.push(null);
  50681. }
  50682. // If interpolate value action
  50683. if (parsedAction.name === "InterpolateValueAction") {
  50684. var param = parameters[parameters.length - 2];
  50685. parameters[parameters.length - 1] = param;
  50686. parameters[parameters.length - 2] = condition;
  50687. }
  50688. // Action or condition(s) and not CombineAction
  50689. var newAction = instanciate(parsedAction.name, parameters);
  50690. if (newAction instanceof BABYLON.Condition && condition !== null) {
  50691. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  50692. if (action)
  50693. action.then(nothing);
  50694. else
  50695. actionManager.registerAction(nothing);
  50696. action = nothing;
  50697. }
  50698. if (combineArray === null) {
  50699. if (newAction instanceof BABYLON.Condition) {
  50700. condition = newAction;
  50701. newAction = action;
  50702. }
  50703. else {
  50704. condition = null;
  50705. if (action)
  50706. action.then(newAction);
  50707. else
  50708. actionManager.registerAction(newAction);
  50709. }
  50710. }
  50711. else {
  50712. combineArray.push(newAction);
  50713. }
  50714. for (var i = 0; i < parsedAction.children.length; i++)
  50715. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  50716. };
  50717. // triggers
  50718. for (var i = 0; i < parsedActions.children.length; i++) {
  50719. var triggerParams;
  50720. var trigger = parsedActions.children[i];
  50721. if (trigger.properties.length > 0) {
  50722. var param = trigger.properties[0].value;
  50723. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  50724. if (value._meshId) {
  50725. value.mesh = scene.getMeshByID(value._meshId);
  50726. }
  50727. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  50728. }
  50729. else
  50730. triggerParams = ActionManager[trigger.name];
  50731. for (var j = 0; j < trigger.children.length; j++) {
  50732. if (!trigger.detached)
  50733. traverse(trigger.children[j], triggerParams, null, null);
  50734. }
  50735. }
  50736. };
  50737. ActionManager.GetTriggerName = function (trigger) {
  50738. switch (trigger) {
  50739. case 0: return "NothingTrigger";
  50740. case 1: return "OnPickTrigger";
  50741. case 2: return "OnLeftPickTrigger";
  50742. case 3: return "OnRightPickTrigger";
  50743. case 4: return "OnCenterPickTrigger";
  50744. case 5: return "OnPickDownTrigger";
  50745. case 6: return "OnPickUpTrigger";
  50746. case 7: return "OnLongPressTrigger";
  50747. case 8: return "OnPointerOverTrigger";
  50748. case 9: return "OnPointerOutTrigger";
  50749. case 10: return "OnEveryFrameTrigger";
  50750. case 11: return "OnIntersectionEnterTrigger";
  50751. case 12: return "OnIntersectionExitTrigger";
  50752. case 13: return "OnKeyDownTrigger";
  50753. case 14: return "OnKeyUpTrigger";
  50754. case 15: return "OnPickOutTrigger";
  50755. default: return "";
  50756. }
  50757. };
  50758. // Statics
  50759. ActionManager._NothingTrigger = 0;
  50760. ActionManager._OnPickTrigger = 1;
  50761. ActionManager._OnLeftPickTrigger = 2;
  50762. ActionManager._OnRightPickTrigger = 3;
  50763. ActionManager._OnCenterPickTrigger = 4;
  50764. ActionManager._OnPickDownTrigger = 5;
  50765. ActionManager._OnDoublePickTrigger = 6;
  50766. ActionManager._OnPickUpTrigger = 7;
  50767. ActionManager._OnLongPressTrigger = 8;
  50768. ActionManager._OnPointerOverTrigger = 9;
  50769. ActionManager._OnPointerOutTrigger = 10;
  50770. ActionManager._OnEveryFrameTrigger = 11;
  50771. ActionManager._OnIntersectionEnterTrigger = 12;
  50772. ActionManager._OnIntersectionExitTrigger = 13;
  50773. ActionManager._OnKeyDownTrigger = 14;
  50774. ActionManager._OnKeyUpTrigger = 15;
  50775. ActionManager._OnPickOutTrigger = 16;
  50776. ActionManager.Triggers = {};
  50777. return ActionManager;
  50778. }());
  50779. BABYLON.ActionManager = ActionManager;
  50780. })(BABYLON || (BABYLON = {}));
  50781. //# sourceMappingURL=babylon.actionManager.js.map
  50782. "use strict";
  50783. var BABYLON;
  50784. (function (BABYLON) {
  50785. var InterpolateValueAction = /** @class */ (function (_super) {
  50786. __extends(InterpolateValueAction, _super);
  50787. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  50788. if (duration === void 0) { duration = 1000; }
  50789. var _this = _super.call(this, triggerOptions, condition) || this;
  50790. _this.propertyPath = propertyPath;
  50791. _this.value = value;
  50792. _this.duration = duration;
  50793. _this.stopOtherAnimations = stopOtherAnimations;
  50794. _this.onInterpolationDone = onInterpolationDone;
  50795. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  50796. _this._target = _this._effectiveTarget = target;
  50797. return _this;
  50798. }
  50799. InterpolateValueAction.prototype._prepare = function () {
  50800. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50801. this._property = this._getProperty(this.propertyPath);
  50802. };
  50803. InterpolateValueAction.prototype.execute = function () {
  50804. var _this = this;
  50805. var scene = this._actionManager.getScene();
  50806. var keys = [
  50807. {
  50808. frame: 0,
  50809. value: this._effectiveTarget[this._property]
  50810. }, {
  50811. frame: 100,
  50812. value: this.value
  50813. }
  50814. ];
  50815. var dataType;
  50816. if (typeof this.value === "number") {
  50817. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  50818. }
  50819. else if (this.value instanceof BABYLON.Color3) {
  50820. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  50821. }
  50822. else if (this.value instanceof BABYLON.Vector3) {
  50823. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  50824. }
  50825. else if (this.value instanceof BABYLON.Matrix) {
  50826. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  50827. }
  50828. else if (this.value instanceof BABYLON.Quaternion) {
  50829. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  50830. }
  50831. else {
  50832. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  50833. return;
  50834. }
  50835. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  50836. animation.setKeys(keys);
  50837. if (this.stopOtherAnimations) {
  50838. scene.stopAnimation(this._effectiveTarget);
  50839. }
  50840. var wrapper = function () {
  50841. _this.onInterpolationDoneObservable.notifyObservers(_this);
  50842. if (_this.onInterpolationDone) {
  50843. _this.onInterpolationDone();
  50844. }
  50845. };
  50846. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  50847. };
  50848. InterpolateValueAction.prototype.serialize = function (parent) {
  50849. return _super.prototype._serialize.call(this, {
  50850. name: "InterpolateValueAction",
  50851. properties: [
  50852. BABYLON.Action._GetTargetProperty(this._target),
  50853. { name: "propertyPath", value: this.propertyPath },
  50854. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  50855. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  50856. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  50857. ]
  50858. }, parent);
  50859. };
  50860. return InterpolateValueAction;
  50861. }(BABYLON.Action));
  50862. BABYLON.InterpolateValueAction = InterpolateValueAction;
  50863. })(BABYLON || (BABYLON = {}));
  50864. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  50865. "use strict";
  50866. var BABYLON;
  50867. (function (BABYLON) {
  50868. var SwitchBooleanAction = /** @class */ (function (_super) {
  50869. __extends(SwitchBooleanAction, _super);
  50870. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  50871. var _this = _super.call(this, triggerOptions, condition) || this;
  50872. _this.propertyPath = propertyPath;
  50873. _this._target = _this._effectiveTarget = target;
  50874. return _this;
  50875. }
  50876. SwitchBooleanAction.prototype._prepare = function () {
  50877. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50878. this._property = this._getProperty(this.propertyPath);
  50879. };
  50880. SwitchBooleanAction.prototype.execute = function () {
  50881. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  50882. };
  50883. SwitchBooleanAction.prototype.serialize = function (parent) {
  50884. return _super.prototype._serialize.call(this, {
  50885. name: "SwitchBooleanAction",
  50886. properties: [
  50887. BABYLON.Action._GetTargetProperty(this._target),
  50888. { name: "propertyPath", value: this.propertyPath }
  50889. ]
  50890. }, parent);
  50891. };
  50892. return SwitchBooleanAction;
  50893. }(BABYLON.Action));
  50894. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  50895. var SetStateAction = /** @class */ (function (_super) {
  50896. __extends(SetStateAction, _super);
  50897. function SetStateAction(triggerOptions, target, value, condition) {
  50898. var _this = _super.call(this, triggerOptions, condition) || this;
  50899. _this.value = value;
  50900. _this._target = target;
  50901. return _this;
  50902. }
  50903. SetStateAction.prototype.execute = function () {
  50904. this._target.state = this.value;
  50905. };
  50906. SetStateAction.prototype.serialize = function (parent) {
  50907. return _super.prototype._serialize.call(this, {
  50908. name: "SetStateAction",
  50909. properties: [
  50910. BABYLON.Action._GetTargetProperty(this._target),
  50911. { name: "value", value: this.value }
  50912. ]
  50913. }, parent);
  50914. };
  50915. return SetStateAction;
  50916. }(BABYLON.Action));
  50917. BABYLON.SetStateAction = SetStateAction;
  50918. var SetValueAction = /** @class */ (function (_super) {
  50919. __extends(SetValueAction, _super);
  50920. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  50921. var _this = _super.call(this, triggerOptions, condition) || this;
  50922. _this.propertyPath = propertyPath;
  50923. _this.value = value;
  50924. _this._target = _this._effectiveTarget = target;
  50925. return _this;
  50926. }
  50927. SetValueAction.prototype._prepare = function () {
  50928. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50929. this._property = this._getProperty(this.propertyPath);
  50930. };
  50931. SetValueAction.prototype.execute = function () {
  50932. this._effectiveTarget[this._property] = this.value;
  50933. if (this._target.markAsDirty) {
  50934. this._target.markAsDirty(this._property);
  50935. }
  50936. };
  50937. SetValueAction.prototype.serialize = function (parent) {
  50938. return _super.prototype._serialize.call(this, {
  50939. name: "SetValueAction",
  50940. properties: [
  50941. BABYLON.Action._GetTargetProperty(this._target),
  50942. { name: "propertyPath", value: this.propertyPath },
  50943. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50944. ]
  50945. }, parent);
  50946. };
  50947. return SetValueAction;
  50948. }(BABYLON.Action));
  50949. BABYLON.SetValueAction = SetValueAction;
  50950. var IncrementValueAction = /** @class */ (function (_super) {
  50951. __extends(IncrementValueAction, _super);
  50952. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  50953. var _this = _super.call(this, triggerOptions, condition) || this;
  50954. _this.propertyPath = propertyPath;
  50955. _this.value = value;
  50956. _this._target = _this._effectiveTarget = target;
  50957. return _this;
  50958. }
  50959. IncrementValueAction.prototype._prepare = function () {
  50960. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50961. this._property = this._getProperty(this.propertyPath);
  50962. if (typeof this._effectiveTarget[this._property] !== "number") {
  50963. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  50964. }
  50965. };
  50966. IncrementValueAction.prototype.execute = function () {
  50967. this._effectiveTarget[this._property] += this.value;
  50968. if (this._target.markAsDirty) {
  50969. this._target.markAsDirty(this._property);
  50970. }
  50971. };
  50972. IncrementValueAction.prototype.serialize = function (parent) {
  50973. return _super.prototype._serialize.call(this, {
  50974. name: "IncrementValueAction",
  50975. properties: [
  50976. BABYLON.Action._GetTargetProperty(this._target),
  50977. { name: "propertyPath", value: this.propertyPath },
  50978. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50979. ]
  50980. }, parent);
  50981. };
  50982. return IncrementValueAction;
  50983. }(BABYLON.Action));
  50984. BABYLON.IncrementValueAction = IncrementValueAction;
  50985. var PlayAnimationAction = /** @class */ (function (_super) {
  50986. __extends(PlayAnimationAction, _super);
  50987. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  50988. var _this = _super.call(this, triggerOptions, condition) || this;
  50989. _this.from = from;
  50990. _this.to = to;
  50991. _this.loop = loop;
  50992. _this._target = target;
  50993. return _this;
  50994. }
  50995. PlayAnimationAction.prototype._prepare = function () {
  50996. };
  50997. PlayAnimationAction.prototype.execute = function () {
  50998. var scene = this._actionManager.getScene();
  50999. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  51000. };
  51001. PlayAnimationAction.prototype.serialize = function (parent) {
  51002. return _super.prototype._serialize.call(this, {
  51003. name: "PlayAnimationAction",
  51004. properties: [
  51005. BABYLON.Action._GetTargetProperty(this._target),
  51006. { name: "from", value: String(this.from) },
  51007. { name: "to", value: String(this.to) },
  51008. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  51009. ]
  51010. }, parent);
  51011. };
  51012. return PlayAnimationAction;
  51013. }(BABYLON.Action));
  51014. BABYLON.PlayAnimationAction = PlayAnimationAction;
  51015. var StopAnimationAction = /** @class */ (function (_super) {
  51016. __extends(StopAnimationAction, _super);
  51017. function StopAnimationAction(triggerOptions, target, condition) {
  51018. var _this = _super.call(this, triggerOptions, condition) || this;
  51019. _this._target = target;
  51020. return _this;
  51021. }
  51022. StopAnimationAction.prototype._prepare = function () {
  51023. };
  51024. StopAnimationAction.prototype.execute = function () {
  51025. var scene = this._actionManager.getScene();
  51026. scene.stopAnimation(this._target);
  51027. };
  51028. StopAnimationAction.prototype.serialize = function (parent) {
  51029. return _super.prototype._serialize.call(this, {
  51030. name: "StopAnimationAction",
  51031. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  51032. }, parent);
  51033. };
  51034. return StopAnimationAction;
  51035. }(BABYLON.Action));
  51036. BABYLON.StopAnimationAction = StopAnimationAction;
  51037. var DoNothingAction = /** @class */ (function (_super) {
  51038. __extends(DoNothingAction, _super);
  51039. function DoNothingAction(triggerOptions, condition) {
  51040. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  51041. return _super.call(this, triggerOptions, condition) || this;
  51042. }
  51043. DoNothingAction.prototype.execute = function () {
  51044. };
  51045. DoNothingAction.prototype.serialize = function (parent) {
  51046. return _super.prototype._serialize.call(this, {
  51047. name: "DoNothingAction",
  51048. properties: []
  51049. }, parent);
  51050. };
  51051. return DoNothingAction;
  51052. }(BABYLON.Action));
  51053. BABYLON.DoNothingAction = DoNothingAction;
  51054. var CombineAction = /** @class */ (function (_super) {
  51055. __extends(CombineAction, _super);
  51056. function CombineAction(triggerOptions, children, condition) {
  51057. var _this = _super.call(this, triggerOptions, condition) || this;
  51058. _this.children = children;
  51059. return _this;
  51060. }
  51061. CombineAction.prototype._prepare = function () {
  51062. for (var index = 0; index < this.children.length; index++) {
  51063. this.children[index]._actionManager = this._actionManager;
  51064. this.children[index]._prepare();
  51065. }
  51066. };
  51067. CombineAction.prototype.execute = function (evt) {
  51068. for (var index = 0; index < this.children.length; index++) {
  51069. this.children[index].execute(evt);
  51070. }
  51071. };
  51072. CombineAction.prototype.serialize = function (parent) {
  51073. var serializationObject = _super.prototype._serialize.call(this, {
  51074. name: "CombineAction",
  51075. properties: [],
  51076. combine: []
  51077. }, parent);
  51078. for (var i = 0; i < this.children.length; i++) {
  51079. serializationObject.combine.push(this.children[i].serialize(null));
  51080. }
  51081. return serializationObject;
  51082. };
  51083. return CombineAction;
  51084. }(BABYLON.Action));
  51085. BABYLON.CombineAction = CombineAction;
  51086. var ExecuteCodeAction = /** @class */ (function (_super) {
  51087. __extends(ExecuteCodeAction, _super);
  51088. function ExecuteCodeAction(triggerOptions, func, condition) {
  51089. var _this = _super.call(this, triggerOptions, condition) || this;
  51090. _this.func = func;
  51091. return _this;
  51092. }
  51093. ExecuteCodeAction.prototype.execute = function (evt) {
  51094. this.func(evt);
  51095. };
  51096. return ExecuteCodeAction;
  51097. }(BABYLON.Action));
  51098. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  51099. var SetParentAction = /** @class */ (function (_super) {
  51100. __extends(SetParentAction, _super);
  51101. function SetParentAction(triggerOptions, target, parent, condition) {
  51102. var _this = _super.call(this, triggerOptions, condition) || this;
  51103. _this._target = target;
  51104. _this._parent = parent;
  51105. return _this;
  51106. }
  51107. SetParentAction.prototype._prepare = function () {
  51108. };
  51109. SetParentAction.prototype.execute = function () {
  51110. if (this._target.parent === this._parent) {
  51111. return;
  51112. }
  51113. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  51114. invertParentWorldMatrix.invert();
  51115. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  51116. this._target.parent = this._parent;
  51117. };
  51118. SetParentAction.prototype.serialize = function (parent) {
  51119. return _super.prototype._serialize.call(this, {
  51120. name: "SetParentAction",
  51121. properties: [
  51122. BABYLON.Action._GetTargetProperty(this._target),
  51123. BABYLON.Action._GetTargetProperty(this._parent),
  51124. ]
  51125. }, parent);
  51126. };
  51127. return SetParentAction;
  51128. }(BABYLON.Action));
  51129. BABYLON.SetParentAction = SetParentAction;
  51130. var PlaySoundAction = /** @class */ (function (_super) {
  51131. __extends(PlaySoundAction, _super);
  51132. function PlaySoundAction(triggerOptions, sound, condition) {
  51133. var _this = _super.call(this, triggerOptions, condition) || this;
  51134. _this._sound = sound;
  51135. return _this;
  51136. }
  51137. PlaySoundAction.prototype._prepare = function () {
  51138. };
  51139. PlaySoundAction.prototype.execute = function () {
  51140. if (this._sound !== undefined)
  51141. this._sound.play();
  51142. };
  51143. PlaySoundAction.prototype.serialize = function (parent) {
  51144. return _super.prototype._serialize.call(this, {
  51145. name: "PlaySoundAction",
  51146. properties: [{ name: "sound", value: this._sound.name }]
  51147. }, parent);
  51148. };
  51149. return PlaySoundAction;
  51150. }(BABYLON.Action));
  51151. BABYLON.PlaySoundAction = PlaySoundAction;
  51152. var StopSoundAction = /** @class */ (function (_super) {
  51153. __extends(StopSoundAction, _super);
  51154. function StopSoundAction(triggerOptions, sound, condition) {
  51155. var _this = _super.call(this, triggerOptions, condition) || this;
  51156. _this._sound = sound;
  51157. return _this;
  51158. }
  51159. StopSoundAction.prototype._prepare = function () {
  51160. };
  51161. StopSoundAction.prototype.execute = function () {
  51162. if (this._sound !== undefined)
  51163. this._sound.stop();
  51164. };
  51165. StopSoundAction.prototype.serialize = function (parent) {
  51166. return _super.prototype._serialize.call(this, {
  51167. name: "StopSoundAction",
  51168. properties: [{ name: "sound", value: this._sound.name }]
  51169. }, parent);
  51170. };
  51171. return StopSoundAction;
  51172. }(BABYLON.Action));
  51173. BABYLON.StopSoundAction = StopSoundAction;
  51174. })(BABYLON || (BABYLON = {}));
  51175. //# sourceMappingURL=babylon.directActions.js.map
  51176. "use strict";
  51177. var BABYLON;
  51178. (function (BABYLON) {
  51179. var SpriteManager = /** @class */ (function () {
  51180. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  51181. if (epsilon === void 0) { epsilon = 0.01; }
  51182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51183. this.name = name;
  51184. this.sprites = new Array();
  51185. this.renderingGroupId = 0;
  51186. this.layerMask = 0x0FFFFFFF;
  51187. this.fogEnabled = true;
  51188. this.isPickable = false;
  51189. /**
  51190. * An event triggered when the manager is disposed.
  51191. */
  51192. this.onDisposeObservable = new BABYLON.Observable();
  51193. this._vertexBuffers = {};
  51194. this._capacity = capacity;
  51195. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  51196. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51197. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51198. if (cellSize.width && cellSize.height) {
  51199. this.cellWidth = cellSize.width;
  51200. this.cellHeight = cellSize.height;
  51201. }
  51202. else if (cellSize !== undefined) {
  51203. this.cellWidth = cellSize;
  51204. this.cellHeight = cellSize;
  51205. }
  51206. else {
  51207. return;
  51208. }
  51209. this._epsilon = epsilon;
  51210. this._scene = scene;
  51211. this._scene.spriteManagers.push(this);
  51212. var indices = [];
  51213. var index = 0;
  51214. for (var count = 0; count < capacity; count++) {
  51215. indices.push(index);
  51216. indices.push(index + 1);
  51217. indices.push(index + 2);
  51218. indices.push(index);
  51219. indices.push(index + 2);
  51220. indices.push(index + 3);
  51221. index += 4;
  51222. }
  51223. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  51224. // VBO
  51225. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  51226. this._vertexData = new Float32Array(capacity * 16 * 4);
  51227. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  51228. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  51229. var options = this._buffer.createVertexBuffer("options", 4, 4);
  51230. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  51231. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  51232. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51233. this._vertexBuffers["options"] = options;
  51234. this._vertexBuffers["cellInfo"] = cellInfo;
  51235. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51236. // Effects
  51237. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  51238. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  51239. }
  51240. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  51241. set: function (callback) {
  51242. if (this._onDisposeObserver) {
  51243. this.onDisposeObservable.remove(this._onDisposeObserver);
  51244. }
  51245. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51246. },
  51247. enumerable: true,
  51248. configurable: true
  51249. });
  51250. Object.defineProperty(SpriteManager.prototype, "texture", {
  51251. get: function () {
  51252. return this._spriteTexture;
  51253. },
  51254. set: function (value) {
  51255. this._spriteTexture = value;
  51256. },
  51257. enumerable: true,
  51258. configurable: true
  51259. });
  51260. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  51261. var arrayOffset = index * 16;
  51262. if (offsetX === 0)
  51263. offsetX = this._epsilon;
  51264. else if (offsetX === 1)
  51265. offsetX = 1 - this._epsilon;
  51266. if (offsetY === 0)
  51267. offsetY = this._epsilon;
  51268. else if (offsetY === 1)
  51269. offsetY = 1 - this._epsilon;
  51270. this._vertexData[arrayOffset] = sprite.position.x;
  51271. this._vertexData[arrayOffset + 1] = sprite.position.y;
  51272. this._vertexData[arrayOffset + 2] = sprite.position.z;
  51273. this._vertexData[arrayOffset + 3] = sprite.angle;
  51274. this._vertexData[arrayOffset + 4] = sprite.width;
  51275. this._vertexData[arrayOffset + 5] = sprite.height;
  51276. this._vertexData[arrayOffset + 6] = offsetX;
  51277. this._vertexData[arrayOffset + 7] = offsetY;
  51278. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  51279. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  51280. var offset = (sprite.cellIndex / rowSize) >> 0;
  51281. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  51282. this._vertexData[arrayOffset + 11] = offset;
  51283. // Color
  51284. this._vertexData[arrayOffset + 12] = sprite.color.r;
  51285. this._vertexData[arrayOffset + 13] = sprite.color.g;
  51286. this._vertexData[arrayOffset + 14] = sprite.color.b;
  51287. this._vertexData[arrayOffset + 15] = sprite.color.a;
  51288. };
  51289. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  51290. var count = Math.min(this._capacity, this.sprites.length);
  51291. var min = BABYLON.Vector3.Zero();
  51292. var max = BABYLON.Vector3.Zero();
  51293. var distance = Number.MAX_VALUE;
  51294. var currentSprite = null;
  51295. var cameraSpacePosition = BABYLON.Vector3.Zero();
  51296. var cameraView = camera.getViewMatrix();
  51297. for (var index = 0; index < count; index++) {
  51298. var sprite = this.sprites[index];
  51299. if (!sprite) {
  51300. continue;
  51301. }
  51302. if (predicate) {
  51303. if (!predicate(sprite)) {
  51304. continue;
  51305. }
  51306. }
  51307. else if (!sprite.isPickable) {
  51308. continue;
  51309. }
  51310. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  51311. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  51312. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  51313. if (ray.intersectsBoxMinMax(min, max)) {
  51314. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  51315. if (distance > currentDistance) {
  51316. distance = currentDistance;
  51317. currentSprite = sprite;
  51318. if (fastCheck) {
  51319. break;
  51320. }
  51321. }
  51322. }
  51323. }
  51324. if (currentSprite) {
  51325. var result = new BABYLON.PickingInfo();
  51326. result.hit = true;
  51327. result.pickedSprite = currentSprite;
  51328. result.distance = distance;
  51329. return result;
  51330. }
  51331. return null;
  51332. };
  51333. SpriteManager.prototype.render = function () {
  51334. // Check
  51335. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  51336. return;
  51337. var engine = this._scene.getEngine();
  51338. var baseSize = this._spriteTexture.getBaseSize();
  51339. // Sprites
  51340. var deltaTime = engine.getDeltaTime();
  51341. var max = Math.min(this._capacity, this.sprites.length);
  51342. var rowSize = baseSize.width / this.cellWidth;
  51343. var offset = 0;
  51344. for (var index = 0; index < max; index++) {
  51345. var sprite = this.sprites[index];
  51346. if (!sprite) {
  51347. continue;
  51348. }
  51349. sprite._animate(deltaTime);
  51350. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  51351. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  51352. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  51353. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  51354. }
  51355. this._buffer.update(this._vertexData);
  51356. // Render
  51357. var effect = this._effectBase;
  51358. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  51359. effect = this._effectFog;
  51360. }
  51361. engine.enableEffect(effect);
  51362. var viewMatrix = this._scene.getViewMatrix();
  51363. effect.setTexture("diffuseSampler", this._spriteTexture);
  51364. effect.setMatrix("view", viewMatrix);
  51365. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51366. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  51367. // Fog
  51368. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  51369. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  51370. effect.setColor3("vFogColor", this._scene.fogColor);
  51371. }
  51372. // VBOs
  51373. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51374. // Draw order
  51375. engine.setDepthFunctionToLessOrEqual();
  51376. effect.setBool("alphaTest", true);
  51377. engine.setColorWrite(false);
  51378. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  51379. engine.setColorWrite(true);
  51380. effect.setBool("alphaTest", false);
  51381. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51382. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  51383. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51384. };
  51385. SpriteManager.prototype.dispose = function () {
  51386. if (this._buffer) {
  51387. this._buffer.dispose();
  51388. this._buffer = null;
  51389. }
  51390. if (this._indexBuffer) {
  51391. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51392. this._indexBuffer = null;
  51393. }
  51394. if (this._spriteTexture) {
  51395. this._spriteTexture.dispose();
  51396. this._spriteTexture = null;
  51397. }
  51398. // Remove from scene
  51399. var index = this._scene.spriteManagers.indexOf(this);
  51400. this._scene.spriteManagers.splice(index, 1);
  51401. // Callback
  51402. this.onDisposeObservable.notifyObservers(this);
  51403. this.onDisposeObservable.clear();
  51404. };
  51405. return SpriteManager;
  51406. }());
  51407. BABYLON.SpriteManager = SpriteManager;
  51408. })(BABYLON || (BABYLON = {}));
  51409. //# sourceMappingURL=babylon.spriteManager.js.map
  51410. "use strict";
  51411. var BABYLON;
  51412. (function (BABYLON) {
  51413. var Sprite = /** @class */ (function () {
  51414. function Sprite(name, manager) {
  51415. this.name = name;
  51416. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51417. this.width = 1.0;
  51418. this.height = 1.0;
  51419. this.angle = 0;
  51420. this.cellIndex = 0;
  51421. this.invertU = 0;
  51422. this.invertV = 0;
  51423. this.animations = new Array();
  51424. this.isPickable = false;
  51425. this._animationStarted = false;
  51426. this._loopAnimation = false;
  51427. this._fromIndex = 0;
  51428. this._toIndex = 0;
  51429. this._delay = 0;
  51430. this._direction = 1;
  51431. this._time = 0;
  51432. this._manager = manager;
  51433. this._manager.sprites.push(this);
  51434. this.position = BABYLON.Vector3.Zero();
  51435. }
  51436. Object.defineProperty(Sprite.prototype, "size", {
  51437. get: function () {
  51438. return this.width;
  51439. },
  51440. set: function (value) {
  51441. this.width = value;
  51442. this.height = value;
  51443. },
  51444. enumerable: true,
  51445. configurable: true
  51446. });
  51447. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  51448. this._fromIndex = from;
  51449. this._toIndex = to;
  51450. this._loopAnimation = loop;
  51451. this._delay = delay;
  51452. this._animationStarted = true;
  51453. this._direction = from < to ? 1 : -1;
  51454. this.cellIndex = from;
  51455. this._time = 0;
  51456. this._onAnimationEnd = onAnimationEnd;
  51457. };
  51458. Sprite.prototype.stopAnimation = function () {
  51459. this._animationStarted = false;
  51460. };
  51461. Sprite.prototype._animate = function (deltaTime) {
  51462. if (!this._animationStarted)
  51463. return;
  51464. this._time += deltaTime;
  51465. if (this._time > this._delay) {
  51466. this._time = this._time % this._delay;
  51467. this.cellIndex += this._direction;
  51468. if (this.cellIndex > this._toIndex) {
  51469. if (this._loopAnimation) {
  51470. this.cellIndex = this._fromIndex;
  51471. }
  51472. else {
  51473. this.cellIndex = this._toIndex;
  51474. this._animationStarted = false;
  51475. if (this._onAnimationEnd) {
  51476. this._onAnimationEnd();
  51477. }
  51478. if (this.disposeWhenFinishedAnimating) {
  51479. this.dispose();
  51480. }
  51481. }
  51482. }
  51483. }
  51484. };
  51485. Sprite.prototype.dispose = function () {
  51486. for (var i = 0; i < this._manager.sprites.length; i++) {
  51487. if (this._manager.sprites[i] == this) {
  51488. this._manager.sprites.splice(i, 1);
  51489. }
  51490. }
  51491. };
  51492. return Sprite;
  51493. }());
  51494. BABYLON.Sprite = Sprite;
  51495. })(BABYLON || (BABYLON = {}));
  51496. //# sourceMappingURL=babylon.sprite.js.map
  51497. "use strict";
  51498. var BABYLON;
  51499. (function (BABYLON) {
  51500. var IntersectionInfo = /** @class */ (function () {
  51501. function IntersectionInfo(bu, bv, distance) {
  51502. this.bu = bu;
  51503. this.bv = bv;
  51504. this.distance = distance;
  51505. this.faceId = 0;
  51506. this.subMeshId = 0;
  51507. }
  51508. return IntersectionInfo;
  51509. }());
  51510. BABYLON.IntersectionInfo = IntersectionInfo;
  51511. var PickingInfo = /** @class */ (function () {
  51512. function PickingInfo() {
  51513. this.hit = false;
  51514. this.distance = 0;
  51515. this.pickedPoint = null;
  51516. this.pickedMesh = null;
  51517. this.bu = 0;
  51518. this.bv = 0;
  51519. this.faceId = -1;
  51520. this.subMeshId = 0;
  51521. this.pickedSprite = null;
  51522. }
  51523. // Methods
  51524. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  51525. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  51526. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  51527. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  51528. return null;
  51529. }
  51530. var indices = this.pickedMesh.getIndices();
  51531. if (!indices) {
  51532. return null;
  51533. }
  51534. var result;
  51535. if (useVerticesNormals) {
  51536. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51537. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  51538. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  51539. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  51540. normal0 = normal0.scale(this.bu);
  51541. normal1 = normal1.scale(this.bv);
  51542. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  51543. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  51544. }
  51545. else {
  51546. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51547. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  51548. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  51549. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  51550. var p1p2 = vertex1.subtract(vertex2);
  51551. var p3p2 = vertex3.subtract(vertex2);
  51552. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  51553. }
  51554. if (useWorldCoordinates) {
  51555. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  51556. }
  51557. return BABYLON.Vector3.Normalize(result);
  51558. };
  51559. PickingInfo.prototype.getTextureCoordinates = function () {
  51560. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51561. return null;
  51562. }
  51563. var indices = this.pickedMesh.getIndices();
  51564. if (!indices) {
  51565. return null;
  51566. }
  51567. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51568. if (!uvs) {
  51569. return null;
  51570. }
  51571. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  51572. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  51573. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  51574. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  51575. uv1 = uv1.scale(this.bu);
  51576. uv2 = uv2.scale(this.bv);
  51577. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  51578. };
  51579. return PickingInfo;
  51580. }());
  51581. BABYLON.PickingInfo = PickingInfo;
  51582. })(BABYLON || (BABYLON = {}));
  51583. //# sourceMappingURL=babylon.pickingInfo.js.map
  51584. "use strict";
  51585. var BABYLON;
  51586. (function (BABYLON) {
  51587. var Ray = /** @class */ (function () {
  51588. function Ray(origin, direction, length) {
  51589. if (length === void 0) { length = Number.MAX_VALUE; }
  51590. this.origin = origin;
  51591. this.direction = direction;
  51592. this.length = length;
  51593. }
  51594. // Methods
  51595. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  51596. var d = 0.0;
  51597. var maxValue = Number.MAX_VALUE;
  51598. var inv;
  51599. var min;
  51600. var max;
  51601. var temp;
  51602. if (Math.abs(this.direction.x) < 0.0000001) {
  51603. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  51604. return false;
  51605. }
  51606. }
  51607. else {
  51608. inv = 1.0 / this.direction.x;
  51609. min = (minimum.x - this.origin.x) * inv;
  51610. max = (maximum.x - this.origin.x) * inv;
  51611. if (max === -Infinity) {
  51612. max = Infinity;
  51613. }
  51614. if (min > max) {
  51615. temp = min;
  51616. min = max;
  51617. max = temp;
  51618. }
  51619. d = Math.max(min, d);
  51620. maxValue = Math.min(max, maxValue);
  51621. if (d > maxValue) {
  51622. return false;
  51623. }
  51624. }
  51625. if (Math.abs(this.direction.y) < 0.0000001) {
  51626. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  51627. return false;
  51628. }
  51629. }
  51630. else {
  51631. inv = 1.0 / this.direction.y;
  51632. min = (minimum.y - this.origin.y) * inv;
  51633. max = (maximum.y - this.origin.y) * inv;
  51634. if (max === -Infinity) {
  51635. max = Infinity;
  51636. }
  51637. if (min > max) {
  51638. temp = min;
  51639. min = max;
  51640. max = temp;
  51641. }
  51642. d = Math.max(min, d);
  51643. maxValue = Math.min(max, maxValue);
  51644. if (d > maxValue) {
  51645. return false;
  51646. }
  51647. }
  51648. if (Math.abs(this.direction.z) < 0.0000001) {
  51649. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  51650. return false;
  51651. }
  51652. }
  51653. else {
  51654. inv = 1.0 / this.direction.z;
  51655. min = (minimum.z - this.origin.z) * inv;
  51656. max = (maximum.z - this.origin.z) * inv;
  51657. if (max === -Infinity) {
  51658. max = Infinity;
  51659. }
  51660. if (min > max) {
  51661. temp = min;
  51662. min = max;
  51663. max = temp;
  51664. }
  51665. d = Math.max(min, d);
  51666. maxValue = Math.min(max, maxValue);
  51667. if (d > maxValue) {
  51668. return false;
  51669. }
  51670. }
  51671. return true;
  51672. };
  51673. Ray.prototype.intersectsBox = function (box) {
  51674. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  51675. };
  51676. Ray.prototype.intersectsSphere = function (sphere) {
  51677. var x = sphere.center.x - this.origin.x;
  51678. var y = sphere.center.y - this.origin.y;
  51679. var z = sphere.center.z - this.origin.z;
  51680. var pyth = (x * x) + (y * y) + (z * z);
  51681. var rr = sphere.radius * sphere.radius;
  51682. if (pyth <= rr) {
  51683. return true;
  51684. }
  51685. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  51686. if (dot < 0.0) {
  51687. return false;
  51688. }
  51689. var temp = pyth - (dot * dot);
  51690. return temp <= rr;
  51691. };
  51692. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  51693. if (!this._edge1) {
  51694. this._edge1 = BABYLON.Vector3.Zero();
  51695. this._edge2 = BABYLON.Vector3.Zero();
  51696. this._pvec = BABYLON.Vector3.Zero();
  51697. this._tvec = BABYLON.Vector3.Zero();
  51698. this._qvec = BABYLON.Vector3.Zero();
  51699. }
  51700. vertex1.subtractToRef(vertex0, this._edge1);
  51701. vertex2.subtractToRef(vertex0, this._edge2);
  51702. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  51703. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  51704. if (det === 0) {
  51705. return null;
  51706. }
  51707. var invdet = 1 / det;
  51708. this.origin.subtractToRef(vertex0, this._tvec);
  51709. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  51710. if (bu < 0 || bu > 1.0) {
  51711. return null;
  51712. }
  51713. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  51714. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  51715. if (bv < 0 || bu + bv > 1.0) {
  51716. return null;
  51717. }
  51718. //check if the distance is longer than the predefined length.
  51719. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  51720. if (distance > this.length) {
  51721. return null;
  51722. }
  51723. return new BABYLON.IntersectionInfo(bu, bv, distance);
  51724. };
  51725. Ray.prototype.intersectsPlane = function (plane) {
  51726. var distance;
  51727. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  51728. if (Math.abs(result1) < 9.99999997475243E-07) {
  51729. return null;
  51730. }
  51731. else {
  51732. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  51733. distance = (-plane.d - result2) / result1;
  51734. if (distance < 0.0) {
  51735. if (distance < -9.99999997475243E-07) {
  51736. return null;
  51737. }
  51738. else {
  51739. return 0;
  51740. }
  51741. }
  51742. return distance;
  51743. }
  51744. };
  51745. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  51746. var tm = BABYLON.Tmp.Matrix[0];
  51747. mesh.getWorldMatrix().invertToRef(tm);
  51748. if (this._tmpRay) {
  51749. Ray.TransformToRef(this, tm, this._tmpRay);
  51750. }
  51751. else {
  51752. this._tmpRay = Ray.Transform(this, tm);
  51753. }
  51754. return mesh.intersects(this._tmpRay, fastCheck);
  51755. };
  51756. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  51757. if (results) {
  51758. results.length = 0;
  51759. }
  51760. else {
  51761. results = [];
  51762. }
  51763. for (var i = 0; i < meshes.length; i++) {
  51764. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  51765. if (pickInfo.hit) {
  51766. results.push(pickInfo);
  51767. }
  51768. }
  51769. results.sort(this._comparePickingInfo);
  51770. return results;
  51771. };
  51772. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  51773. if (pickingInfoA.distance < pickingInfoB.distance) {
  51774. return -1;
  51775. }
  51776. else if (pickingInfoA.distance > pickingInfoB.distance) {
  51777. return 1;
  51778. }
  51779. else {
  51780. return 0;
  51781. }
  51782. };
  51783. /**
  51784. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  51785. * @param sega the first point of the segment to test the intersection against
  51786. * @param segb the second point of the segment to test the intersection against
  51787. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  51788. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  51789. */
  51790. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  51791. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  51792. var u = segb.subtract(sega);
  51793. var v = rsegb.subtract(this.origin);
  51794. var w = sega.subtract(this.origin);
  51795. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  51796. var b = BABYLON.Vector3.Dot(u, v);
  51797. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  51798. var d = BABYLON.Vector3.Dot(u, w);
  51799. var e = BABYLON.Vector3.Dot(v, w);
  51800. var D = a * c - b * b; // always >= 0
  51801. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  51802. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  51803. // compute the line parameters of the two closest points
  51804. if (D < Ray.smallnum) {
  51805. sN = 0.0; // force using point P0 on segment S1
  51806. sD = 1.0; // to prevent possible division by 0.0 later
  51807. tN = e;
  51808. tD = c;
  51809. }
  51810. else {
  51811. sN = (b * e - c * d);
  51812. tN = (a * e - b * d);
  51813. if (sN < 0.0) {
  51814. sN = 0.0;
  51815. tN = e;
  51816. tD = c;
  51817. }
  51818. else if (sN > sD) {
  51819. sN = sD;
  51820. tN = e + b;
  51821. tD = c;
  51822. }
  51823. }
  51824. if (tN < 0.0) {
  51825. tN = 0.0;
  51826. // recompute sc for this edge
  51827. if (-d < 0.0) {
  51828. sN = 0.0;
  51829. }
  51830. else if (-d > a)
  51831. sN = sD;
  51832. else {
  51833. sN = -d;
  51834. sD = a;
  51835. }
  51836. }
  51837. else if (tN > tD) {
  51838. tN = tD;
  51839. // recompute sc for this edge
  51840. if ((-d + b) < 0.0) {
  51841. sN = 0;
  51842. }
  51843. else if ((-d + b) > a) {
  51844. sN = sD;
  51845. }
  51846. else {
  51847. sN = (-d + b);
  51848. sD = a;
  51849. }
  51850. }
  51851. // finally do the division to get sc and tc
  51852. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  51853. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  51854. // get the difference of the two closest points
  51855. var qtc = v.multiplyByFloats(tc, tc, tc);
  51856. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  51857. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  51858. if (isIntersected) {
  51859. return qtc.length();
  51860. }
  51861. return -1;
  51862. };
  51863. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  51864. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  51865. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  51866. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  51867. this.direction.normalize();
  51868. return this;
  51869. };
  51870. // Statics
  51871. Ray.Zero = function () {
  51872. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  51873. };
  51874. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  51875. var result = Ray.Zero();
  51876. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  51877. };
  51878. /**
  51879. * 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
  51880. * transformed to the given world matrix.
  51881. * @param origin The origin point
  51882. * @param end The end point
  51883. * @param world a matrix to transform the ray to. Default is the identity matrix.
  51884. */
  51885. Ray.CreateNewFromTo = function (origin, end, world) {
  51886. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  51887. var direction = end.subtract(origin);
  51888. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  51889. direction.normalize();
  51890. return Ray.Transform(new Ray(origin, direction, length), world);
  51891. };
  51892. Ray.Transform = function (ray, matrix) {
  51893. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  51894. Ray.TransformToRef(ray, matrix, result);
  51895. return result;
  51896. };
  51897. Ray.TransformToRef = function (ray, matrix, result) {
  51898. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  51899. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  51900. result.length = ray.length;
  51901. var dir = result.direction;
  51902. var len = dir.length();
  51903. if (!(len === 0 || len === 1)) {
  51904. var num = 1.0 / len;
  51905. dir.x *= num;
  51906. dir.y *= num;
  51907. dir.z *= num;
  51908. result.length *= len;
  51909. }
  51910. };
  51911. Ray.smallnum = 0.00000001;
  51912. Ray.rayl = 10e8;
  51913. return Ray;
  51914. }());
  51915. BABYLON.Ray = Ray;
  51916. })(BABYLON || (BABYLON = {}));
  51917. //# sourceMappingURL=babylon.ray.js.map
  51918. "use strict";
  51919. var BABYLON;
  51920. (function (BABYLON) {
  51921. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  51922. if (boxMin.x > sphereCenter.x + sphereRadius)
  51923. return false;
  51924. if (sphereCenter.x - sphereRadius > boxMax.x)
  51925. return false;
  51926. if (boxMin.y > sphereCenter.y + sphereRadius)
  51927. return false;
  51928. if (sphereCenter.y - sphereRadius > boxMax.y)
  51929. return false;
  51930. if (boxMin.z > sphereCenter.z + sphereRadius)
  51931. return false;
  51932. if (sphereCenter.z - sphereRadius > boxMax.z)
  51933. return false;
  51934. return true;
  51935. };
  51936. var getLowestRoot = (function () {
  51937. var result = { root: 0, found: false };
  51938. return function (a, b, c, maxR) {
  51939. result.root = 0;
  51940. result.found = false;
  51941. var determinant = b * b - 4.0 * a * c;
  51942. if (determinant < 0)
  51943. return result;
  51944. var sqrtD = Math.sqrt(determinant);
  51945. var r1 = (-b - sqrtD) / (2.0 * a);
  51946. var r2 = (-b + sqrtD) / (2.0 * a);
  51947. if (r1 > r2) {
  51948. var temp = r2;
  51949. r2 = r1;
  51950. r1 = temp;
  51951. }
  51952. if (r1 > 0 && r1 < maxR) {
  51953. result.root = r1;
  51954. result.found = true;
  51955. return result;
  51956. }
  51957. if (r2 > 0 && r2 < maxR) {
  51958. result.root = r2;
  51959. result.found = true;
  51960. return result;
  51961. }
  51962. return result;
  51963. };
  51964. })();
  51965. var Collider = /** @class */ (function () {
  51966. function Collider() {
  51967. this._collisionPoint = BABYLON.Vector3.Zero();
  51968. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  51969. this._tempVector = BABYLON.Vector3.Zero();
  51970. this._tempVector2 = BABYLON.Vector3.Zero();
  51971. this._tempVector3 = BABYLON.Vector3.Zero();
  51972. this._tempVector4 = BABYLON.Vector3.Zero();
  51973. this._edge = BABYLON.Vector3.Zero();
  51974. this._baseToVertex = BABYLON.Vector3.Zero();
  51975. this._destinationPoint = BABYLON.Vector3.Zero();
  51976. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  51977. this._displacementVector = BABYLON.Vector3.Zero();
  51978. this._radius = BABYLON.Vector3.One();
  51979. this._retry = 0;
  51980. this._basePointWorld = BABYLON.Vector3.Zero();
  51981. this._velocityWorld = BABYLON.Vector3.Zero();
  51982. this._normalizedVelocity = BABYLON.Vector3.Zero();
  51983. this._collisionMask = -1;
  51984. }
  51985. Object.defineProperty(Collider.prototype, "collisionMask", {
  51986. get: function () {
  51987. return this._collisionMask;
  51988. },
  51989. set: function (mask) {
  51990. this._collisionMask = !isNaN(mask) ? mask : -1;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  51996. /**
  51997. * Gets the plane normal used to compute the sliding response (in local space)
  51998. */
  51999. get: function () {
  52000. return this._slidePlaneNormal;
  52001. },
  52002. enumerable: true,
  52003. configurable: true
  52004. });
  52005. // Methods
  52006. Collider.prototype._initialize = function (source, dir, e) {
  52007. this._velocity = dir;
  52008. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  52009. this._basePoint = source;
  52010. source.multiplyToRef(this._radius, this._basePointWorld);
  52011. dir.multiplyToRef(this._radius, this._velocityWorld);
  52012. this._velocityWorldLength = this._velocityWorld.length();
  52013. this._epsilon = e;
  52014. this.collisionFound = false;
  52015. };
  52016. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  52017. pa.subtractToRef(point, this._tempVector);
  52018. pb.subtractToRef(point, this._tempVector2);
  52019. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  52020. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  52021. if (d < 0)
  52022. return false;
  52023. pc.subtractToRef(point, this._tempVector3);
  52024. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  52025. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  52026. if (d < 0)
  52027. return false;
  52028. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  52029. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  52030. return d >= 0;
  52031. };
  52032. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  52033. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  52034. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  52035. if (distance > this._velocityWorldLength + max + sphereRadius) {
  52036. return false;
  52037. }
  52038. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  52039. return false;
  52040. return true;
  52041. };
  52042. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  52043. var t0;
  52044. var embeddedInPlane = false;
  52045. //defensive programming, actually not needed.
  52046. if (!trianglePlaneArray) {
  52047. trianglePlaneArray = [];
  52048. }
  52049. if (!trianglePlaneArray[faceIndex]) {
  52050. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  52051. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  52052. }
  52053. var trianglePlane = trianglePlaneArray[faceIndex];
  52054. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  52055. return;
  52056. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  52057. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  52058. if (normalDotVelocity == 0) {
  52059. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  52060. return;
  52061. embeddedInPlane = true;
  52062. t0 = 0;
  52063. }
  52064. else {
  52065. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  52066. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  52067. if (t0 > t1) {
  52068. var temp = t1;
  52069. t1 = t0;
  52070. t0 = temp;
  52071. }
  52072. if (t0 > 1.0 || t1 < 0.0)
  52073. return;
  52074. if (t0 < 0)
  52075. t0 = 0;
  52076. if (t0 > 1.0)
  52077. t0 = 1.0;
  52078. }
  52079. this._collisionPoint.copyFromFloats(0, 0, 0);
  52080. var found = false;
  52081. var t = 1.0;
  52082. if (!embeddedInPlane) {
  52083. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  52084. this._velocity.scaleToRef(t0, this._tempVector);
  52085. this._planeIntersectionPoint.addInPlace(this._tempVector);
  52086. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  52087. found = true;
  52088. t = t0;
  52089. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  52090. }
  52091. }
  52092. if (!found) {
  52093. var velocitySquaredLength = this._velocity.lengthSquared();
  52094. var a = velocitySquaredLength;
  52095. this._basePoint.subtractToRef(p1, this._tempVector);
  52096. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  52097. var c = this._tempVector.lengthSquared() - 1.0;
  52098. var lowestRoot = getLowestRoot(a, b, c, t);
  52099. if (lowestRoot.found) {
  52100. t = lowestRoot.root;
  52101. found = true;
  52102. this._collisionPoint.copyFrom(p1);
  52103. }
  52104. this._basePoint.subtractToRef(p2, this._tempVector);
  52105. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  52106. c = this._tempVector.lengthSquared() - 1.0;
  52107. lowestRoot = getLowestRoot(a, b, c, t);
  52108. if (lowestRoot.found) {
  52109. t = lowestRoot.root;
  52110. found = true;
  52111. this._collisionPoint.copyFrom(p2);
  52112. }
  52113. this._basePoint.subtractToRef(p3, this._tempVector);
  52114. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  52115. c = this._tempVector.lengthSquared() - 1.0;
  52116. lowestRoot = getLowestRoot(a, b, c, t);
  52117. if (lowestRoot.found) {
  52118. t = lowestRoot.root;
  52119. found = true;
  52120. this._collisionPoint.copyFrom(p3);
  52121. }
  52122. p2.subtractToRef(p1, this._edge);
  52123. p1.subtractToRef(this._basePoint, this._baseToVertex);
  52124. var edgeSquaredLength = this._edge.lengthSquared();
  52125. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  52126. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  52127. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  52128. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  52129. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  52130. lowestRoot = getLowestRoot(a, b, c, t);
  52131. if (lowestRoot.found) {
  52132. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  52133. if (f >= 0.0 && f <= 1.0) {
  52134. t = lowestRoot.root;
  52135. found = true;
  52136. this._edge.scaleInPlace(f);
  52137. p1.addToRef(this._edge, this._collisionPoint);
  52138. }
  52139. }
  52140. p3.subtractToRef(p2, this._edge);
  52141. p2.subtractToRef(this._basePoint, this._baseToVertex);
  52142. edgeSquaredLength = this._edge.lengthSquared();
  52143. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  52144. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  52145. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  52146. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  52147. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  52148. lowestRoot = getLowestRoot(a, b, c, t);
  52149. if (lowestRoot.found) {
  52150. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  52151. if (f >= 0.0 && f <= 1.0) {
  52152. t = lowestRoot.root;
  52153. found = true;
  52154. this._edge.scaleInPlace(f);
  52155. p2.addToRef(this._edge, this._collisionPoint);
  52156. }
  52157. }
  52158. p1.subtractToRef(p3, this._edge);
  52159. p3.subtractToRef(this._basePoint, this._baseToVertex);
  52160. edgeSquaredLength = this._edge.lengthSquared();
  52161. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  52162. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  52163. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  52164. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  52165. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  52166. lowestRoot = getLowestRoot(a, b, c, t);
  52167. if (lowestRoot.found) {
  52168. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  52169. if (f >= 0.0 && f <= 1.0) {
  52170. t = lowestRoot.root;
  52171. found = true;
  52172. this._edge.scaleInPlace(f);
  52173. p3.addToRef(this._edge, this._collisionPoint);
  52174. }
  52175. }
  52176. }
  52177. if (found) {
  52178. var distToCollision = t * this._velocity.length();
  52179. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  52180. if (!this.intersectionPoint) {
  52181. this.intersectionPoint = this._collisionPoint.clone();
  52182. }
  52183. else {
  52184. this.intersectionPoint.copyFrom(this._collisionPoint);
  52185. }
  52186. this._nearestDistance = distToCollision;
  52187. this.collisionFound = true;
  52188. }
  52189. }
  52190. };
  52191. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  52192. for (var i = indexStart; i < indexEnd; i += 3) {
  52193. var p1 = pts[indices[i] - decal];
  52194. var p2 = pts[indices[i + 1] - decal];
  52195. var p3 = pts[indices[i + 2] - decal];
  52196. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  52197. }
  52198. };
  52199. Collider.prototype._getResponse = function (pos, vel) {
  52200. pos.addToRef(vel, this._destinationPoint);
  52201. vel.scaleInPlace((this._nearestDistance / vel.length()));
  52202. this._basePoint.addToRef(vel, pos);
  52203. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  52204. this._slidePlaneNormal.normalize();
  52205. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  52206. pos.addInPlace(this._displacementVector);
  52207. this.intersectionPoint.addInPlace(this._displacementVector);
  52208. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  52209. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  52210. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  52211. };
  52212. return Collider;
  52213. }());
  52214. BABYLON.Collider = Collider;
  52215. })(BABYLON || (BABYLON = {}));
  52216. //# sourceMappingURL=babylon.collider.js.map
  52217. "use strict";
  52218. var BABYLON;
  52219. (function (BABYLON) {
  52220. //WebWorker code will be inserted to this variable.
  52221. BABYLON.CollisionWorker = "";
  52222. var WorkerTaskType;
  52223. (function (WorkerTaskType) {
  52224. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  52225. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  52226. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  52227. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  52228. var WorkerReplyType;
  52229. (function (WorkerReplyType) {
  52230. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  52231. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  52232. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  52233. var CollisionCoordinatorWorker = /** @class */ (function () {
  52234. function CollisionCoordinatorWorker() {
  52235. var _this = this;
  52236. this._scaledPosition = BABYLON.Vector3.Zero();
  52237. this._scaledVelocity = BABYLON.Vector3.Zero();
  52238. this.onMeshUpdated = function (transformNode) {
  52239. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  52240. };
  52241. this.onGeometryUpdated = function (geometry) {
  52242. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  52243. };
  52244. this._afterRender = function () {
  52245. if (!_this._init)
  52246. return;
  52247. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  52248. return;
  52249. }
  52250. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  52251. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  52252. if (_this._runningUpdated > 4) {
  52253. return;
  52254. }
  52255. ++_this._runningUpdated;
  52256. var payload = {
  52257. updatedMeshes: _this._addUpdateMeshesList,
  52258. updatedGeometries: _this._addUpdateGeometriesList,
  52259. removedGeometries: _this._toRemoveGeometryArray,
  52260. removedMeshes: _this._toRemoveMeshesArray
  52261. };
  52262. var message = {
  52263. payload: payload,
  52264. taskType: WorkerTaskType.UPDATE
  52265. };
  52266. var serializable = [];
  52267. for (var id in payload.updatedGeometries) {
  52268. if (payload.updatedGeometries.hasOwnProperty(id)) {
  52269. //prepare transferables
  52270. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  52271. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  52272. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  52273. }
  52274. }
  52275. _this._worker.postMessage(message, serializable);
  52276. _this._addUpdateMeshesList = {};
  52277. _this._addUpdateGeometriesList = {};
  52278. _this._toRemoveGeometryArray = [];
  52279. _this._toRemoveMeshesArray = [];
  52280. };
  52281. this._onMessageFromWorker = function (e) {
  52282. var returnData = e.data;
  52283. if (returnData.error != WorkerReplyType.SUCCESS) {
  52284. //TODO what errors can be returned from the worker?
  52285. BABYLON.Tools.Warn("error returned from worker!");
  52286. return;
  52287. }
  52288. switch (returnData.taskType) {
  52289. case WorkerTaskType.INIT:
  52290. _this._init = true;
  52291. //Update the worked with ALL of the scene's current state
  52292. _this._scene.meshes.forEach(function (mesh) {
  52293. _this.onMeshAdded(mesh);
  52294. });
  52295. _this._scene.getGeometries().forEach(function (geometry) {
  52296. _this.onGeometryAdded(geometry);
  52297. });
  52298. break;
  52299. case WorkerTaskType.UPDATE:
  52300. _this._runningUpdated--;
  52301. break;
  52302. case WorkerTaskType.COLLIDE:
  52303. var returnPayload = returnData.payload;
  52304. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  52305. return;
  52306. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  52307. if (callback) {
  52308. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  52309. if (mesh) {
  52310. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  52311. }
  52312. }
  52313. //cleanup
  52314. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  52315. break;
  52316. }
  52317. };
  52318. this._collisionsCallbackArray = [];
  52319. this._init = false;
  52320. this._runningUpdated = 0;
  52321. this._addUpdateMeshesList = {};
  52322. this._addUpdateGeometriesList = {};
  52323. this._toRemoveGeometryArray = [];
  52324. this._toRemoveMeshesArray = [];
  52325. }
  52326. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  52327. if (!this._init)
  52328. return;
  52329. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  52330. return;
  52331. position.divideToRef(collider._radius, this._scaledPosition);
  52332. displacement.divideToRef(collider._radius, this._scaledVelocity);
  52333. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  52334. var payload = {
  52335. collider: {
  52336. position: this._scaledPosition.asArray(),
  52337. velocity: this._scaledVelocity.asArray(),
  52338. radius: collider._radius.asArray()
  52339. },
  52340. collisionId: collisionIndex,
  52341. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  52342. maximumRetry: maximumRetry
  52343. };
  52344. var message = {
  52345. payload: payload,
  52346. taskType: WorkerTaskType.COLLIDE
  52347. };
  52348. this._worker.postMessage(message);
  52349. };
  52350. CollisionCoordinatorWorker.prototype.init = function (scene) {
  52351. this._scene = scene;
  52352. this._scene.registerAfterRender(this._afterRender);
  52353. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  52354. this._worker = new Worker(workerUrl);
  52355. this._worker.onmessage = this._onMessageFromWorker;
  52356. var message = {
  52357. payload: {},
  52358. taskType: WorkerTaskType.INIT
  52359. };
  52360. this._worker.postMessage(message);
  52361. };
  52362. CollisionCoordinatorWorker.prototype.destroy = function () {
  52363. this._scene.unregisterAfterRender(this._afterRender);
  52364. this._worker.terminate();
  52365. };
  52366. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  52367. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  52368. this.onMeshUpdated(mesh);
  52369. };
  52370. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  52371. this._toRemoveMeshesArray.push(mesh.uniqueId);
  52372. };
  52373. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  52374. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  52375. geometry.onGeometryUpdated = this.onGeometryUpdated;
  52376. this.onGeometryUpdated(geometry);
  52377. };
  52378. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  52379. this._toRemoveGeometryArray.push(geometry.id);
  52380. };
  52381. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  52382. var submeshes = [];
  52383. if (mesh.subMeshes) {
  52384. submeshes = mesh.subMeshes.map(function (sm, idx) {
  52385. var boundingInfo = sm.getBoundingInfo();
  52386. return {
  52387. position: idx,
  52388. verticesStart: sm.verticesStart,
  52389. verticesCount: sm.verticesCount,
  52390. indexStart: sm.indexStart,
  52391. indexCount: sm.indexCount,
  52392. hasMaterial: !!sm.getMaterial(),
  52393. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  52394. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  52395. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  52396. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  52397. };
  52398. });
  52399. }
  52400. var geometryId = null;
  52401. if (mesh instanceof BABYLON.Mesh) {
  52402. var geometry = mesh.geometry;
  52403. geometryId = geometry ? geometry.id : null;
  52404. }
  52405. else if (mesh instanceof BABYLON.InstancedMesh) {
  52406. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  52407. geometryId = geometry ? geometry.id : null;
  52408. }
  52409. var boundingInfo = mesh.getBoundingInfo();
  52410. return {
  52411. uniqueId: mesh.uniqueId,
  52412. id: mesh.id,
  52413. name: mesh.name,
  52414. geometryId: geometryId,
  52415. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  52416. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  52417. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  52418. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  52419. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  52420. subMeshes: submeshes,
  52421. checkCollisions: mesh.checkCollisions
  52422. };
  52423. };
  52424. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  52425. return {
  52426. id: geometry.id,
  52427. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  52428. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  52429. indices: new Uint32Array(geometry.getIndices() || []),
  52430. };
  52431. };
  52432. return CollisionCoordinatorWorker;
  52433. }());
  52434. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  52435. var CollisionCoordinatorLegacy = /** @class */ (function () {
  52436. function CollisionCoordinatorLegacy() {
  52437. this._scaledPosition = BABYLON.Vector3.Zero();
  52438. this._scaledVelocity = BABYLON.Vector3.Zero();
  52439. this._finalPosition = BABYLON.Vector3.Zero();
  52440. }
  52441. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  52442. position.divideToRef(collider._radius, this._scaledPosition);
  52443. displacement.divideToRef(collider._radius, this._scaledVelocity);
  52444. collider.collidedMesh = null;
  52445. collider._retry = 0;
  52446. collider._initialVelocity = this._scaledVelocity;
  52447. collider._initialPosition = this._scaledPosition;
  52448. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  52449. this._finalPosition.multiplyInPlace(collider._radius);
  52450. //run the callback
  52451. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  52452. };
  52453. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  52454. this._scene = scene;
  52455. };
  52456. CollisionCoordinatorLegacy.prototype.destroy = function () {
  52457. //Legacy need no destruction method.
  52458. };
  52459. //No update in legacy mode
  52460. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  52461. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  52462. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  52463. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  52464. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  52465. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  52466. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  52467. if (excludedMesh === void 0) { excludedMesh = null; }
  52468. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  52469. if (collider._retry >= maximumRetry) {
  52470. finalPosition.copyFrom(position);
  52471. return;
  52472. }
  52473. // Check if this is a mesh else camera or -1
  52474. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  52475. collider._initialize(position, velocity, closeDistance);
  52476. // Check all meshes
  52477. for (var index = 0; index < this._scene.meshes.length; index++) {
  52478. var mesh = this._scene.meshes[index];
  52479. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  52480. mesh._checkCollision(collider);
  52481. }
  52482. }
  52483. if (!collider.collisionFound) {
  52484. position.addToRef(velocity, finalPosition);
  52485. return;
  52486. }
  52487. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  52488. collider._getResponse(position, velocity);
  52489. }
  52490. if (velocity.length() <= closeDistance) {
  52491. finalPosition.copyFrom(position);
  52492. return;
  52493. }
  52494. collider._retry++;
  52495. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  52496. };
  52497. return CollisionCoordinatorLegacy;
  52498. }());
  52499. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  52500. })(BABYLON || (BABYLON = {}));
  52501. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  52502. "use strict";
  52503. var BABYLON;
  52504. (function (BABYLON) {
  52505. /**
  52506. * A particle represents one of the element emitted by a particle system.
  52507. * This is mainly define by its coordinates, direction, velocity and age.
  52508. */
  52509. var Particle = /** @class */ (function () {
  52510. /**
  52511. * Creates a new instance Particle
  52512. * @param particleSystem the particle system the particle belongs to
  52513. */
  52514. function Particle(
  52515. /**
  52516. * particleSystem the particle system the particle belongs to.
  52517. */
  52518. particleSystem) {
  52519. this.particleSystem = particleSystem;
  52520. /**
  52521. * The world position of the particle in the scene.
  52522. */
  52523. this.position = BABYLON.Vector3.Zero();
  52524. /**
  52525. * The world direction of the particle in the scene.
  52526. */
  52527. this.direction = BABYLON.Vector3.Zero();
  52528. /**
  52529. * The color of the particle.
  52530. */
  52531. this.color = new BABYLON.Color4(0, 0, 0, 0);
  52532. /**
  52533. * The color change of the particle per step.
  52534. */
  52535. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  52536. /**
  52537. * Defines how long will the life of the particle be.
  52538. */
  52539. this.lifeTime = 1.0;
  52540. /**
  52541. * The current age of the particle.
  52542. */
  52543. this.age = 0;
  52544. /**
  52545. * The current size of the particle.
  52546. */
  52547. this.size = 0;
  52548. /**
  52549. * The current angle of the particle.
  52550. */
  52551. this.angle = 0;
  52552. /**
  52553. * Defines how fast is the angle changing.
  52554. */
  52555. this.angularSpeed = 0;
  52556. /**
  52557. * Defines the cell index used by the particle to be rendered from a sprite.
  52558. */
  52559. this.cellIndex = 0;
  52560. this._currentFrameCounter = 0;
  52561. if (!this.particleSystem.isAnimationSheetEnabled) {
  52562. return;
  52563. }
  52564. this.updateCellInfoFromSystem();
  52565. }
  52566. Particle.prototype.updateCellInfoFromSystem = function () {
  52567. this.cellIndex = this.particleSystem.startSpriteCellID;
  52568. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  52569. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  52570. }
  52571. else {
  52572. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  52573. }
  52574. };
  52575. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  52576. // (ageOffset / scaledUpdateSpeed) / available cells
  52577. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  52578. this._currentFrameCounter += scaledUpdateSpeed;
  52579. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  52580. this._currentFrameCounter = 0;
  52581. this.cellIndex++;
  52582. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  52583. this.cellIndex = this.particleSystem.endSpriteCellID;
  52584. }
  52585. }
  52586. };
  52587. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  52588. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  52589. this.cellIndex++;
  52590. this._currentFrameCounter = 0;
  52591. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  52592. if (this.particleSystem.spriteCellLoop) {
  52593. this.cellIndex = this.particleSystem.startSpriteCellID;
  52594. }
  52595. else {
  52596. this.cellIndex = this.particleSystem.endSpriteCellID;
  52597. }
  52598. }
  52599. }
  52600. else {
  52601. this._currentFrameCounter++;
  52602. }
  52603. };
  52604. /**
  52605. * Copy the properties of particle to another one.
  52606. * @param other the particle to copy the information to.
  52607. */
  52608. Particle.prototype.copyTo = function (other) {
  52609. other.position.copyFrom(this.position);
  52610. other.direction.copyFrom(this.direction);
  52611. other.color.copyFrom(this.color);
  52612. other.colorStep.copyFrom(this.colorStep);
  52613. other.lifeTime = this.lifeTime;
  52614. other.age = this.age;
  52615. other.size = this.size;
  52616. other.angle = this.angle;
  52617. other.angularSpeed = this.angularSpeed;
  52618. other.particleSystem = this.particleSystem;
  52619. other.cellIndex = this.cellIndex;
  52620. };
  52621. return Particle;
  52622. }());
  52623. BABYLON.Particle = Particle;
  52624. })(BABYLON || (BABYLON = {}));
  52625. //# sourceMappingURL=babylon.particle.js.map
  52626. "use strict";
  52627. var BABYLON;
  52628. (function (BABYLON) {
  52629. /**
  52630. * This represents a particle system in Babylon.
  52631. * 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.
  52632. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  52633. * @example https://doc.babylonjs.com/babylon101/particles
  52634. */
  52635. var ParticleSystem = /** @class */ (function () {
  52636. /**
  52637. * Instantiates a particle system.
  52638. * 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.
  52639. * @param name The name of the particle system
  52640. * @param capacity The max number of particles alive at the same time
  52641. * @param scene The scene the particle system belongs to
  52642. * @param customEffect a custom effect used to change the way particles are rendered by default
  52643. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  52644. * @param epsilon Offset used to render the particles
  52645. */
  52646. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  52647. if (customEffect === void 0) { customEffect = null; }
  52648. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  52649. if (epsilon === void 0) { epsilon = 0.01; }
  52650. var _this = this;
  52651. /**
  52652. * List of animations used by the particle system.
  52653. */
  52654. this.animations = [];
  52655. /**
  52656. * The rendering group used by the Particle system to chose when to render.
  52657. */
  52658. this.renderingGroupId = 0;
  52659. /**
  52660. * The emitter represents the Mesh or position we are attaching the particle system to.
  52661. */
  52662. this.emitter = null;
  52663. /**
  52664. * The maximum number of particles to emit per frame
  52665. */
  52666. this.emitRate = 10;
  52667. /**
  52668. * If you want to launch only a few particles at once, that can be done, as well.
  52669. */
  52670. this.manualEmitCount = -1;
  52671. /**
  52672. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52673. */
  52674. this.updateSpeed = 0.01;
  52675. /**
  52676. * The amount of time the particle system is running (depends of the overall update speed).
  52677. */
  52678. this.targetStopDuration = 0;
  52679. /**
  52680. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  52681. */
  52682. this.disposeOnStop = false;
  52683. /**
  52684. * Minimum power of emitting particles.
  52685. */
  52686. this.minEmitPower = 1;
  52687. /**
  52688. * Maximum power of emitting particles.
  52689. */
  52690. this.maxEmitPower = 1;
  52691. /**
  52692. * Minimum life time of emitting particles.
  52693. */
  52694. this.minLifeTime = 1;
  52695. /**
  52696. * Maximum life time of emitting particles.
  52697. */
  52698. this.maxLifeTime = 1;
  52699. /**
  52700. * Minimum Size of emitting particles.
  52701. */
  52702. this.minSize = 1;
  52703. /**
  52704. * Maximum Size of emitting particles.
  52705. */
  52706. this.maxSize = 1;
  52707. /**
  52708. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  52709. */
  52710. this.minAngularSpeed = 0;
  52711. /**
  52712. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  52713. */
  52714. this.maxAngularSpeed = 0;
  52715. /**
  52716. * The layer mask we are rendering the particles through.
  52717. */
  52718. this.layerMask = 0x0FFFFFFF;
  52719. /**
  52720. * This can help using your own shader to render the particle system.
  52721. * The according effect will be created
  52722. */
  52723. this.customShader = null;
  52724. /**
  52725. * By default particle system starts as soon as they are created. This prevents the
  52726. * automatic start to happen and let you decide when to start emitting particles.
  52727. */
  52728. this.preventAutoStart = false;
  52729. /**
  52730. * Callback triggered when the particle animation is ending.
  52731. */
  52732. this.onAnimationEnd = null;
  52733. /**
  52734. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52735. */
  52736. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  52737. /**
  52738. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52739. * to override the particles.
  52740. */
  52741. this.forceDepthWrite = false;
  52742. /**
  52743. * You can use gravity if you want to give an orientation to your particles.
  52744. */
  52745. this.gravity = BABYLON.Vector3.Zero();
  52746. /**
  52747. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52748. */
  52749. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52750. /**
  52751. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52752. */
  52753. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52754. /**
  52755. * Color the particle will have at the end of its lifetime.
  52756. */
  52757. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  52758. /**
  52759. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  52760. */
  52761. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52762. /**
  52763. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  52764. */
  52765. this.spriteCellLoop = true;
  52766. /**
  52767. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  52768. */
  52769. this.spriteCellChangeSpeed = 0;
  52770. /**
  52771. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  52772. */
  52773. this.startSpriteCellID = 0;
  52774. /**
  52775. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  52776. */
  52777. this.endSpriteCellID = 0;
  52778. /**
  52779. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  52780. */
  52781. this.spriteCellWidth = 0;
  52782. /**
  52783. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  52784. */
  52785. this.spriteCellHeight = 0;
  52786. /**
  52787. * An event triggered when the system is disposed.
  52788. */
  52789. this.onDisposeObservable = new BABYLON.Observable();
  52790. this._particles = new Array();
  52791. this._stockParticles = new Array();
  52792. this._newPartsExcess = 0;
  52793. this._vertexBuffers = {};
  52794. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  52795. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  52796. this._scaledDirection = BABYLON.Vector3.Zero();
  52797. this._scaledGravity = BABYLON.Vector3.Zero();
  52798. this._currentRenderId = -1;
  52799. this._started = false;
  52800. this._stopped = false;
  52801. this._actualFrame = 0;
  52802. this._vertexBufferSize = 11;
  52803. // start of sub system methods
  52804. /**
  52805. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  52806. * Its lifetime will start back at 0.
  52807. */
  52808. this.recycleParticle = function (particle) {
  52809. var lastParticle = _this._particles.pop();
  52810. if (lastParticle !== particle) {
  52811. lastParticle.copyTo(particle);
  52812. }
  52813. _this._stockParticles.push(lastParticle);
  52814. };
  52815. this._createParticle = function () {
  52816. var particle;
  52817. if (_this._stockParticles.length !== 0) {
  52818. particle = _this._stockParticles.pop();
  52819. particle.age = 0;
  52820. particle.cellIndex = _this.startSpriteCellID;
  52821. }
  52822. else {
  52823. particle = new BABYLON.Particle(_this);
  52824. }
  52825. return particle;
  52826. };
  52827. this._emitFromParticle = function (particle) {
  52828. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  52829. return;
  52830. }
  52831. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  52832. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  52833. subSystem._rootParticleSystem = _this;
  52834. _this.activeSubSystems.push(subSystem);
  52835. subSystem.start();
  52836. };
  52837. this._appendParticleVertexes = null;
  52838. this.id = name;
  52839. this.name = name;
  52840. this._capacity = capacity;
  52841. this._epsilon = epsilon;
  52842. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  52843. if (isAnimationSheetEnabled) {
  52844. this._vertexBufferSize = 12;
  52845. }
  52846. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52847. this._customEffect = customEffect;
  52848. scene.particleSystems.push(this);
  52849. this._createIndexBuffer();
  52850. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  52851. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  52852. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  52853. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  52854. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  52855. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  52856. if (this._isAnimationSheetEnabled) {
  52857. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  52858. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  52859. }
  52860. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  52861. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  52862. this._vertexBuffers["options"] = options;
  52863. // Default emitter type
  52864. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52865. this.updateFunction = function (particles) {
  52866. for (var index = 0; index < particles.length; index++) {
  52867. var particle = particles[index];
  52868. particle.age += _this._scaledUpdateSpeed;
  52869. if (particle.age >= particle.lifeTime) {
  52870. _this._emitFromParticle(particle);
  52871. _this.recycleParticle(particle);
  52872. index--;
  52873. continue;
  52874. }
  52875. else {
  52876. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  52877. particle.color.addInPlace(_this._scaledColorStep);
  52878. if (particle.color.a < 0)
  52879. particle.color.a = 0;
  52880. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  52881. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  52882. particle.position.addInPlace(_this._scaledDirection);
  52883. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  52884. particle.direction.addInPlace(_this._scaledGravity);
  52885. if (_this._isAnimationSheetEnabled) {
  52886. particle.updateCellIndex(_this._scaledUpdateSpeed);
  52887. }
  52888. }
  52889. }
  52890. };
  52891. }
  52892. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  52893. /**
  52894. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52895. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52896. */
  52897. get: function () {
  52898. if (this.particleEmitterType.direction1) {
  52899. return this.particleEmitterType.direction1;
  52900. }
  52901. return BABYLON.Vector3.Zero();
  52902. },
  52903. set: function (value) {
  52904. if (this.particleEmitterType.direction1) {
  52905. this.particleEmitterType.direction1 = value;
  52906. }
  52907. },
  52908. enumerable: true,
  52909. configurable: true
  52910. });
  52911. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  52912. /**
  52913. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52914. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52915. */
  52916. get: function () {
  52917. if (this.particleEmitterType.direction2) {
  52918. return this.particleEmitterType.direction2;
  52919. }
  52920. return BABYLON.Vector3.Zero();
  52921. },
  52922. set: function (value) {
  52923. if (this.particleEmitterType.direction2) {
  52924. this.particleEmitterType.direction2 = value;
  52925. }
  52926. },
  52927. enumerable: true,
  52928. configurable: true
  52929. });
  52930. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  52931. /**
  52932. * 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.
  52933. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52934. */
  52935. get: function () {
  52936. if (this.particleEmitterType.minEmitBox) {
  52937. return this.particleEmitterType.minEmitBox;
  52938. }
  52939. return BABYLON.Vector3.Zero();
  52940. },
  52941. set: function (value) {
  52942. if (this.particleEmitterType.minEmitBox) {
  52943. this.particleEmitterType.minEmitBox = value;
  52944. }
  52945. },
  52946. enumerable: true,
  52947. configurable: true
  52948. });
  52949. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  52950. /**
  52951. * 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.
  52952. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52953. */
  52954. get: function () {
  52955. if (this.particleEmitterType.maxEmitBox) {
  52956. return this.particleEmitterType.maxEmitBox;
  52957. }
  52958. return BABYLON.Vector3.Zero();
  52959. },
  52960. set: function (value) {
  52961. if (this.particleEmitterType.maxEmitBox) {
  52962. this.particleEmitterType.maxEmitBox = value;
  52963. }
  52964. },
  52965. enumerable: true,
  52966. configurable: true
  52967. });
  52968. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  52969. /**
  52970. * Sets a callback that will be triggered when the system is disposed.
  52971. */
  52972. set: function (callback) {
  52973. if (this._onDisposeObserver) {
  52974. this.onDisposeObservable.remove(this._onDisposeObserver);
  52975. }
  52976. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52977. },
  52978. enumerable: true,
  52979. configurable: true
  52980. });
  52981. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  52982. /**
  52983. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  52984. */
  52985. get: function () {
  52986. return this._isAnimationSheetEnabled;
  52987. },
  52988. enumerable: true,
  52989. configurable: true
  52990. });
  52991. Object.defineProperty(ParticleSystem.prototype, "particles", {
  52992. //end of Sub-emitter
  52993. /**
  52994. * Gets the current list of active particles
  52995. */
  52996. get: function () {
  52997. return this._particles;
  52998. },
  52999. enumerable: true,
  53000. configurable: true
  53001. });
  53002. /**
  53003. * Returns the string "ParticleSystem"
  53004. * @returns a string containing the class name
  53005. */
  53006. ParticleSystem.prototype.getClassName = function () {
  53007. return "ParticleSystem";
  53008. };
  53009. ParticleSystem.prototype._createIndexBuffer = function () {
  53010. var indices = [];
  53011. var index = 0;
  53012. for (var count = 0; count < this._capacity; count++) {
  53013. indices.push(index);
  53014. indices.push(index + 1);
  53015. indices.push(index + 2);
  53016. indices.push(index);
  53017. indices.push(index + 2);
  53018. indices.push(index + 3);
  53019. index += 4;
  53020. }
  53021. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  53022. };
  53023. /**
  53024. * Gets the maximum number of particles active at the same time.
  53025. * @returns The max number of active particles.
  53026. */
  53027. ParticleSystem.prototype.getCapacity = function () {
  53028. return this._capacity;
  53029. };
  53030. /**
  53031. * Gets Wether there are still active particles in the system.
  53032. * @returns True if it is alive, otherwise false.
  53033. */
  53034. ParticleSystem.prototype.isAlive = function () {
  53035. return this._alive;
  53036. };
  53037. /**
  53038. * Gets Wether the system has been started.
  53039. * @returns True if it has been started, otherwise false.
  53040. */
  53041. ParticleSystem.prototype.isStarted = function () {
  53042. return this._started;
  53043. };
  53044. /**
  53045. * Starts the particle system and begins to emit.
  53046. */
  53047. ParticleSystem.prototype.start = function () {
  53048. this._started = true;
  53049. this._stopped = false;
  53050. this._actualFrame = 0;
  53051. if (this.subEmitters && this.subEmitters.length != 0) {
  53052. this.activeSubSystems = new Array();
  53053. }
  53054. };
  53055. /**
  53056. * Stops the particle system.
  53057. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  53058. */
  53059. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  53060. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  53061. this._stopped = true;
  53062. if (stopSubEmitters) {
  53063. this._stopSubEmitters();
  53064. }
  53065. };
  53066. // animation sheet
  53067. /**
  53068. * Remove all active particles
  53069. */
  53070. ParticleSystem.prototype.reset = function () {
  53071. this._stockParticles = [];
  53072. this._particles = [];
  53073. };
  53074. /**
  53075. * @ignore (for internal use only)
  53076. */
  53077. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  53078. var offset = index * this._vertexBufferSize;
  53079. this._vertexData[offset] = particle.position.x;
  53080. this._vertexData[offset + 1] = particle.position.y;
  53081. this._vertexData[offset + 2] = particle.position.z;
  53082. this._vertexData[offset + 3] = particle.color.r;
  53083. this._vertexData[offset + 4] = particle.color.g;
  53084. this._vertexData[offset + 5] = particle.color.b;
  53085. this._vertexData[offset + 6] = particle.color.a;
  53086. this._vertexData[offset + 7] = particle.angle;
  53087. this._vertexData[offset + 8] = particle.size;
  53088. this._vertexData[offset + 9] = offsetX;
  53089. this._vertexData[offset + 10] = offsetY;
  53090. };
  53091. /**
  53092. * @ignore (for internal use only)
  53093. */
  53094. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  53095. if (offsetX === 0)
  53096. offsetX = this._epsilon;
  53097. else if (offsetX === 1)
  53098. offsetX = 1 - this._epsilon;
  53099. if (offsetY === 0)
  53100. offsetY = this._epsilon;
  53101. else if (offsetY === 1)
  53102. offsetY = 1 - this._epsilon;
  53103. var offset = index * this._vertexBufferSize;
  53104. this._vertexData[offset] = particle.position.x;
  53105. this._vertexData[offset + 1] = particle.position.y;
  53106. this._vertexData[offset + 2] = particle.position.z;
  53107. this._vertexData[offset + 3] = particle.color.r;
  53108. this._vertexData[offset + 4] = particle.color.g;
  53109. this._vertexData[offset + 5] = particle.color.b;
  53110. this._vertexData[offset + 6] = particle.color.a;
  53111. this._vertexData[offset + 7] = particle.angle;
  53112. this._vertexData[offset + 8] = particle.size;
  53113. this._vertexData[offset + 9] = offsetX;
  53114. this._vertexData[offset + 10] = offsetY;
  53115. this._vertexData[offset + 11] = particle.cellIndex;
  53116. };
  53117. ParticleSystem.prototype._stopSubEmitters = function () {
  53118. if (!this.activeSubSystems) {
  53119. return;
  53120. }
  53121. this.activeSubSystems.forEach(function (subSystem) {
  53122. subSystem.stop(true);
  53123. });
  53124. this.activeSubSystems = new Array();
  53125. };
  53126. ParticleSystem.prototype._removeFromRoot = function () {
  53127. if (!this._rootParticleSystem) {
  53128. return;
  53129. }
  53130. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  53131. if (index !== -1) {
  53132. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  53133. }
  53134. };
  53135. // end of sub system methods
  53136. ParticleSystem.prototype._update = function (newParticles) {
  53137. // Update current
  53138. this._alive = this._particles.length > 0;
  53139. this.updateFunction(this._particles);
  53140. // Add new ones
  53141. var worldMatrix;
  53142. if (this.emitter.position) {
  53143. var emitterMesh = this.emitter;
  53144. worldMatrix = emitterMesh.getWorldMatrix();
  53145. }
  53146. else {
  53147. var emitterPosition = this.emitter;
  53148. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53149. }
  53150. var particle;
  53151. for (var index = 0; index < newParticles; index++) {
  53152. if (this._particles.length === this._capacity) {
  53153. break;
  53154. }
  53155. particle = this._createParticle();
  53156. this._particles.push(particle);
  53157. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  53158. if (this.startPositionFunction) {
  53159. this.startPositionFunction(worldMatrix, particle.position, particle);
  53160. }
  53161. else {
  53162. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  53163. }
  53164. if (this.startDirectionFunction) {
  53165. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  53166. }
  53167. else {
  53168. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  53169. }
  53170. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  53171. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  53172. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  53173. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  53174. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  53175. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  53176. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  53177. }
  53178. };
  53179. ParticleSystem.prototype._getEffect = function () {
  53180. if (this._customEffect) {
  53181. return this._customEffect;
  53182. }
  53183. ;
  53184. var defines = [];
  53185. if (this._scene.clipPlane) {
  53186. defines.push("#define CLIPPLANE");
  53187. }
  53188. if (this._isAnimationSheetEnabled) {
  53189. defines.push("#define ANIMATESHEET");
  53190. }
  53191. // Effect
  53192. var join = defines.join("\n");
  53193. if (this._cachedDefines !== join) {
  53194. this._cachedDefines = join;
  53195. var attributesNamesOrOptions;
  53196. var effectCreationOption;
  53197. if (this._isAnimationSheetEnabled) {
  53198. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  53199. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  53200. }
  53201. else {
  53202. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  53203. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  53204. }
  53205. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  53206. }
  53207. return this._effect;
  53208. };
  53209. /**
  53210. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53211. */
  53212. ParticleSystem.prototype.animate = function () {
  53213. if (!this._started)
  53214. return;
  53215. var effect = this._getEffect();
  53216. // Check
  53217. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  53218. return;
  53219. if (this._currentRenderId === this._scene.getRenderId()) {
  53220. return;
  53221. }
  53222. this._currentRenderId = this._scene.getRenderId();
  53223. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  53224. // determine the number of particles we need to create
  53225. var newParticles;
  53226. if (this.manualEmitCount > -1) {
  53227. newParticles = this.manualEmitCount;
  53228. this._newPartsExcess = 0;
  53229. this.manualEmitCount = 0;
  53230. }
  53231. else {
  53232. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  53233. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  53234. }
  53235. if (this._newPartsExcess > 1.0) {
  53236. newParticles += this._newPartsExcess >> 0;
  53237. this._newPartsExcess -= this._newPartsExcess >> 0;
  53238. }
  53239. this._alive = false;
  53240. if (!this._stopped) {
  53241. this._actualFrame += this._scaledUpdateSpeed;
  53242. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  53243. this.stop();
  53244. }
  53245. else {
  53246. newParticles = 0;
  53247. }
  53248. this._update(newParticles);
  53249. // Stopped?
  53250. if (this._stopped) {
  53251. if (!this._alive) {
  53252. this._started = false;
  53253. if (this.onAnimationEnd) {
  53254. this.onAnimationEnd();
  53255. }
  53256. if (this.disposeOnStop) {
  53257. this._scene._toBeDisposed.push(this);
  53258. }
  53259. }
  53260. }
  53261. // Animation sheet
  53262. if (this._isAnimationSheetEnabled) {
  53263. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  53264. }
  53265. else {
  53266. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  53267. }
  53268. // Update VBO
  53269. var offset = 0;
  53270. for (var index = 0; index < this._particles.length; index++) {
  53271. var particle = this._particles[index];
  53272. this._appendParticleVertexes(offset, particle);
  53273. offset += 4;
  53274. }
  53275. if (this._vertexBuffer) {
  53276. this._vertexBuffer.update(this._vertexData);
  53277. }
  53278. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  53279. this.stop();
  53280. }
  53281. };
  53282. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  53283. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  53284. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  53285. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  53286. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  53287. };
  53288. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  53289. this._appendParticleVertex(offset++, particle, 0, 0);
  53290. this._appendParticleVertex(offset++, particle, 1, 0);
  53291. this._appendParticleVertex(offset++, particle, 1, 1);
  53292. this._appendParticleVertex(offset++, particle, 0, 1);
  53293. };
  53294. /**
  53295. * Rebuilds the particle system.
  53296. */
  53297. ParticleSystem.prototype.rebuild = function () {
  53298. this._createIndexBuffer();
  53299. if (this._vertexBuffer) {
  53300. this._vertexBuffer._rebuild();
  53301. }
  53302. };
  53303. /**
  53304. * Is this system ready to be used/rendered
  53305. * @return true if the system is ready
  53306. */
  53307. ParticleSystem.prototype.isReady = function () {
  53308. var effect = this._getEffect();
  53309. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53310. return false;
  53311. }
  53312. return true;
  53313. };
  53314. /**
  53315. * Renders the particle system in its current state.
  53316. * @returns the current number of particles
  53317. */
  53318. ParticleSystem.prototype.render = function () {
  53319. var effect = this._getEffect();
  53320. // Check
  53321. if (!this.isReady() || !this._particles.length) {
  53322. return 0;
  53323. }
  53324. var engine = this._scene.getEngine();
  53325. // Render
  53326. engine.enableEffect(effect);
  53327. engine.setState(false);
  53328. var viewMatrix = this._scene.getViewMatrix();
  53329. effect.setTexture("diffuseSampler", this.particleTexture);
  53330. effect.setMatrix("view", viewMatrix);
  53331. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53332. if (this._isAnimationSheetEnabled && this.particleTexture) {
  53333. var baseSize = this.particleTexture.getBaseSize();
  53334. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  53335. }
  53336. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  53337. if (this._scene.clipPlane) {
  53338. var clipPlane = this._scene.clipPlane;
  53339. var invView = viewMatrix.clone();
  53340. invView.invert();
  53341. effect.setMatrix("invView", invView);
  53342. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53343. }
  53344. // VBOs
  53345. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53346. // Draw order
  53347. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  53348. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53349. }
  53350. else {
  53351. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53352. }
  53353. if (this.forceDepthWrite) {
  53354. engine.setDepthWrite(true);
  53355. }
  53356. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  53357. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53358. return this._particles.length;
  53359. };
  53360. /**
  53361. * Disposes the particle system and free the associated resources
  53362. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53363. */
  53364. ParticleSystem.prototype.dispose = function (disposeTexture) {
  53365. if (disposeTexture === void 0) { disposeTexture = true; }
  53366. if (this._vertexBuffer) {
  53367. this._vertexBuffer.dispose();
  53368. this._vertexBuffer = null;
  53369. }
  53370. if (this._indexBuffer) {
  53371. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53372. this._indexBuffer = null;
  53373. }
  53374. if (disposeTexture && this.particleTexture) {
  53375. this.particleTexture.dispose();
  53376. this.particleTexture = null;
  53377. }
  53378. this._removeFromRoot();
  53379. // Remove from scene
  53380. var index = this._scene.particleSystems.indexOf(this);
  53381. if (index > -1) {
  53382. this._scene.particleSystems.splice(index, 1);
  53383. }
  53384. // Callback
  53385. this.onDisposeObservable.notifyObservers(this);
  53386. this.onDisposeObservable.clear();
  53387. };
  53388. /**
  53389. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  53390. * @param radius The radius of the sphere to emit from
  53391. * @returns the emitter
  53392. */
  53393. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  53394. if (radius === void 0) { radius = 1; }
  53395. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  53396. this.particleEmitterType = particleEmitter;
  53397. return particleEmitter;
  53398. };
  53399. /**
  53400. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  53401. * @param radius The radius of the sphere to emit from
  53402. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  53403. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  53404. * @returns the emitter
  53405. */
  53406. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  53407. if (radius === void 0) { radius = 1; }
  53408. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  53409. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  53410. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  53411. this.particleEmitterType = particleEmitter;
  53412. return particleEmitter;
  53413. };
  53414. /**
  53415. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  53416. * @param radius The radius of the cone to emit from
  53417. * @param angle The base angle of the cone
  53418. * @returns the emitter
  53419. */
  53420. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  53421. if (radius === void 0) { radius = 1; }
  53422. if (angle === void 0) { angle = Math.PI / 4; }
  53423. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  53424. this.particleEmitterType = particleEmitter;
  53425. return particleEmitter;
  53426. };
  53427. // 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.
  53428. /**
  53429. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  53430. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  53431. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  53432. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  53433. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  53434. * @returns the emitter
  53435. */
  53436. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  53437. var particleEmitter = new BABYLON.BoxParticleEmitter();
  53438. this.particleEmitterType = particleEmitter;
  53439. this.direction1 = direction1;
  53440. this.direction2 = direction2;
  53441. this.minEmitBox = minEmitBox;
  53442. this.maxEmitBox = maxEmitBox;
  53443. return particleEmitter;
  53444. };
  53445. // Clone
  53446. /**
  53447. * Clones the particle system.
  53448. * @param name The name of the cloned object
  53449. * @param newEmitter The new emitter to use
  53450. * @returns the cloned particle system
  53451. */
  53452. ParticleSystem.prototype.clone = function (name, newEmitter) {
  53453. var custom = null;
  53454. var program = null;
  53455. if (this.customShader != null) {
  53456. program = this.customShader;
  53457. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  53458. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  53459. }
  53460. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  53461. result.customShader = program;
  53462. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  53463. if (newEmitter === undefined) {
  53464. newEmitter = this.emitter;
  53465. }
  53466. result.emitter = newEmitter;
  53467. if (this.particleTexture) {
  53468. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53469. }
  53470. if (!this.preventAutoStart) {
  53471. result.start();
  53472. }
  53473. return result;
  53474. };
  53475. /**
  53476. * Serializes the particle system to a JSON object.
  53477. * @returns the JSON object
  53478. */
  53479. ParticleSystem.prototype.serialize = function () {
  53480. var serializationObject = {};
  53481. serializationObject.name = this.name;
  53482. serializationObject.id = this.id;
  53483. // Emitter
  53484. if (this.emitter.position) {
  53485. var emitterMesh = this.emitter;
  53486. serializationObject.emitterId = emitterMesh.id;
  53487. }
  53488. else {
  53489. var emitterPosition = this.emitter;
  53490. serializationObject.emitter = emitterPosition.asArray();
  53491. }
  53492. serializationObject.capacity = this.getCapacity();
  53493. if (this.particleTexture) {
  53494. serializationObject.textureName = this.particleTexture.name;
  53495. }
  53496. // Animations
  53497. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53498. // Particle system
  53499. serializationObject.minAngularSpeed = this.minAngularSpeed;
  53500. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  53501. serializationObject.minSize = this.minSize;
  53502. serializationObject.maxSize = this.maxSize;
  53503. serializationObject.minEmitPower = this.minEmitPower;
  53504. serializationObject.maxEmitPower = this.maxEmitPower;
  53505. serializationObject.minLifeTime = this.minLifeTime;
  53506. serializationObject.maxLifeTime = this.maxLifeTime;
  53507. serializationObject.emitRate = this.emitRate;
  53508. serializationObject.minEmitBox = this.minEmitBox.asArray();
  53509. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  53510. serializationObject.gravity = this.gravity.asArray();
  53511. serializationObject.direction1 = this.direction1.asArray();
  53512. serializationObject.direction2 = this.direction2.asArray();
  53513. serializationObject.color1 = this.color1.asArray();
  53514. serializationObject.color2 = this.color2.asArray();
  53515. serializationObject.colorDead = this.colorDead.asArray();
  53516. serializationObject.updateSpeed = this.updateSpeed;
  53517. serializationObject.targetStopDuration = this.targetStopDuration;
  53518. serializationObject.textureMask = this.textureMask.asArray();
  53519. serializationObject.blendMode = this.blendMode;
  53520. serializationObject.customShader = this.customShader;
  53521. serializationObject.preventAutoStart = this.preventAutoStart;
  53522. serializationObject.startSpriteCellID = this.startSpriteCellID;
  53523. serializationObject.endSpriteCellID = this.endSpriteCellID;
  53524. serializationObject.spriteCellLoop = this.spriteCellLoop;
  53525. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  53526. serializationObject.spriteCellWidth = this.spriteCellWidth;
  53527. serializationObject.spriteCellHeight = this.spriteCellHeight;
  53528. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  53529. // Emitter
  53530. if (this.particleEmitterType) {
  53531. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53532. }
  53533. return serializationObject;
  53534. };
  53535. /**
  53536. * Parses a JSON object to create a particle system.
  53537. * @param parsedParticleSystem The JSON object to parse
  53538. * @param scene The scene to create the particle system in
  53539. * @param rootUrl The root url to use to load external dependencies like texture
  53540. * @returns the Parsed particle system
  53541. */
  53542. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53543. var name = parsedParticleSystem.name;
  53544. var custom = null;
  53545. var program = null;
  53546. if (parsedParticleSystem.customShader) {
  53547. program = parsedParticleSystem.customShader;
  53548. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  53549. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  53550. }
  53551. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  53552. particleSystem.customShader = program;
  53553. if (parsedParticleSystem.id) {
  53554. particleSystem.id = parsedParticleSystem.id;
  53555. }
  53556. // Auto start
  53557. if (parsedParticleSystem.preventAutoStart) {
  53558. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  53559. }
  53560. // Texture
  53561. if (parsedParticleSystem.textureName) {
  53562. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53563. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53564. }
  53565. // Emitter
  53566. if (parsedParticleSystem.emitterId) {
  53567. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53568. }
  53569. else {
  53570. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53571. }
  53572. // Animations
  53573. if (parsedParticleSystem.animations) {
  53574. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53575. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53576. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53577. }
  53578. }
  53579. if (parsedParticleSystem.autoAnimate) {
  53580. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  53581. }
  53582. // Particle system
  53583. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  53584. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  53585. particleSystem.minSize = parsedParticleSystem.minSize;
  53586. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53587. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53588. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53589. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53590. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53591. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53592. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  53593. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  53594. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53595. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  53596. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  53597. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53598. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53599. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53600. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53601. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53602. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  53603. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53604. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  53605. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  53606. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  53607. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  53608. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  53609. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  53610. if (!particleSystem.preventAutoStart) {
  53611. particleSystem.start();
  53612. }
  53613. return particleSystem;
  53614. };
  53615. /**
  53616. * Source color is added to the destination color without alpha affecting the result.
  53617. */
  53618. ParticleSystem.BLENDMODE_ONEONE = 0;
  53619. /**
  53620. * Blend current color and particle color using particle’s alpha.
  53621. */
  53622. ParticleSystem.BLENDMODE_STANDARD = 1;
  53623. return ParticleSystem;
  53624. }());
  53625. BABYLON.ParticleSystem = ParticleSystem;
  53626. })(BABYLON || (BABYLON = {}));
  53627. //# sourceMappingURL=babylon.particleSystem.js.map
  53628. "use strict";
  53629. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  53630. "use strict";
  53631. var BABYLON;
  53632. (function (BABYLON) {
  53633. /**
  53634. * Particle emitter emitting particles from the inside of a box.
  53635. * It emits the particles randomly between 2 given directions.
  53636. */
  53637. var BoxParticleEmitter = /** @class */ (function () {
  53638. /**
  53639. * Creates a new instance BoxParticleEmitter
  53640. */
  53641. function BoxParticleEmitter() {
  53642. /**
  53643. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53644. */
  53645. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  53646. /**
  53647. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53648. */
  53649. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  53650. /**
  53651. * 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.
  53652. */
  53653. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  53654. /**
  53655. * 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.
  53656. */
  53657. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  53658. }
  53659. /**
  53660. * Called by the particle System when the direction is computed for the created particle.
  53661. * @param emitPower is the power of the particle (speed)
  53662. * @param worldMatrix is the world matrix of the particle system
  53663. * @param directionToUpdate is the direction vector to update with the result
  53664. * @param particle is the particle we are computed the direction for
  53665. */
  53666. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53667. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53668. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53669. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53670. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53671. };
  53672. /**
  53673. * Called by the particle System when the position is computed for the created particle.
  53674. * @param worldMatrix is the world matrix of the particle system
  53675. * @param positionToUpdate is the position vector to update with the result
  53676. * @param particle is the particle we are computed the position for
  53677. */
  53678. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53679. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  53680. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  53681. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  53682. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53683. };
  53684. /**
  53685. * Clones the current emitter and returns a copy of it
  53686. * @returns the new emitter
  53687. */
  53688. BoxParticleEmitter.prototype.clone = function () {
  53689. var newOne = new BoxParticleEmitter();
  53690. BABYLON.Tools.DeepCopy(this, newOne);
  53691. return newOne;
  53692. };
  53693. /**
  53694. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53695. * @param effect defines the update shader
  53696. */
  53697. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  53698. effect.setVector3("direction1", this.direction1);
  53699. effect.setVector3("direction2", this.direction2);
  53700. effect.setVector3("minEmitBox", this.minEmitBox);
  53701. effect.setVector3("maxEmitBox", this.maxEmitBox);
  53702. };
  53703. /**
  53704. * Returns a string to use to update the GPU particles update shader
  53705. * @returns a string containng the defines string
  53706. */
  53707. BoxParticleEmitter.prototype.getEffectDefines = function () {
  53708. return "#define BOXEMITTER";
  53709. };
  53710. /**
  53711. * Returns the string "BoxEmitter"
  53712. * @returns a string containing the class name
  53713. */
  53714. BoxParticleEmitter.prototype.getClassName = function () {
  53715. return "BoxEmitter";
  53716. };
  53717. /**
  53718. * Serializes the particle system to a JSON object.
  53719. * @returns the JSON object
  53720. */
  53721. BoxParticleEmitter.prototype.serialize = function () {
  53722. var serializationObject = {};
  53723. serializationObject.type = this.getClassName();
  53724. serializationObject.direction1 = this.direction1.asArray();
  53725. ;
  53726. serializationObject.direction2 = this.direction2.asArray();
  53727. ;
  53728. serializationObject.minEmitBox = this.minEmitBox.asArray();
  53729. ;
  53730. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  53731. ;
  53732. return serializationObject;
  53733. };
  53734. /**
  53735. * Parse properties from a JSON object
  53736. * @param serializationObject defines the JSON object
  53737. */
  53738. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  53739. this.direction1.copyFrom(serializationObject.direction1);
  53740. this.direction2.copyFrom(serializationObject.direction2);
  53741. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  53742. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  53743. };
  53744. return BoxParticleEmitter;
  53745. }());
  53746. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  53747. })(BABYLON || (BABYLON = {}));
  53748. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  53749. "use strict";
  53750. var BABYLON;
  53751. (function (BABYLON) {
  53752. /**
  53753. * Particle emitter emitting particles from the inside of a cone.
  53754. * It emits the particles alongside the cone volume from the base to the particle.
  53755. * The emission direction might be randomized.
  53756. */
  53757. var ConeParticleEmitter = /** @class */ (function () {
  53758. /**
  53759. * Creates a new instance ConeParticleEmitter
  53760. * @param radius the radius of the emission cone (1 by default)
  53761. * @param angles the cone base angle (PI by default)
  53762. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  53763. */
  53764. function ConeParticleEmitter(radius,
  53765. /**
  53766. * The radius of the emission cone.
  53767. */
  53768. angle,
  53769. /**
  53770. * The cone base angle.
  53771. */
  53772. directionRandomizer) {
  53773. if (radius === void 0) { radius = 1; }
  53774. if (angle === void 0) { angle = Math.PI; }
  53775. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  53776. this.angle = angle;
  53777. this.directionRandomizer = directionRandomizer;
  53778. this.radius = radius;
  53779. }
  53780. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  53781. /**
  53782. * Gets the radius of the emission cone.
  53783. */
  53784. get: function () {
  53785. return this._radius;
  53786. },
  53787. /**
  53788. * Sets the radius of the emission cone.
  53789. */
  53790. set: function (value) {
  53791. this._radius = value;
  53792. if (this.angle !== 0) {
  53793. this._height = value / Math.tan(this.angle / 2);
  53794. }
  53795. else {
  53796. this._height = 1;
  53797. }
  53798. },
  53799. enumerable: true,
  53800. configurable: true
  53801. });
  53802. /**
  53803. * Called by the particle System when the direction is computed for the created particle.
  53804. * @param emitPower is the power of the particle (speed)
  53805. * @param worldMatrix is the world matrix of the particle system
  53806. * @param directionToUpdate is the direction vector to update with the result
  53807. * @param particle is the particle we are computed the direction for
  53808. */
  53809. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53810. if (this.angle === 0) {
  53811. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  53812. }
  53813. else {
  53814. // measure the direction Vector from the emitter to the particle.
  53815. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  53816. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53817. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53818. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53819. direction.x += randX;
  53820. direction.y += randY;
  53821. direction.z += randZ;
  53822. direction.normalize();
  53823. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  53824. }
  53825. };
  53826. /**
  53827. * Called by the particle System when the position is computed for the created particle.
  53828. * @param worldMatrix is the world matrix of the particle system
  53829. * @param positionToUpdate is the position vector to update with the result
  53830. * @param particle is the particle we are computed the position for
  53831. */
  53832. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53833. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  53834. var h = BABYLON.Scalar.RandomRange(0, 1);
  53835. // Better distribution in a cone at normal angles.
  53836. h = 1 - h * h;
  53837. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  53838. radius = radius * h;
  53839. var randX = radius * Math.sin(s);
  53840. var randZ = radius * Math.cos(s);
  53841. var randY = h * this._height;
  53842. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53843. };
  53844. /**
  53845. * Clones the current emitter and returns a copy of it
  53846. * @returns the new emitter
  53847. */
  53848. ConeParticleEmitter.prototype.clone = function () {
  53849. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  53850. BABYLON.Tools.DeepCopy(this, newOne);
  53851. return newOne;
  53852. };
  53853. /**
  53854. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53855. * @param effect defines the update shader
  53856. */
  53857. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  53858. effect.setFloat("radius", this.radius);
  53859. effect.setFloat("angle", this.angle);
  53860. effect.setFloat("height", this._height);
  53861. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53862. };
  53863. /**
  53864. * Returns a string to use to update the GPU particles update shader
  53865. * @returns a string containng the defines string
  53866. */
  53867. ConeParticleEmitter.prototype.getEffectDefines = function () {
  53868. return "#define CONEEMITTER";
  53869. };
  53870. /**
  53871. * Returns the string "BoxEmitter"
  53872. * @returns a string containing the class name
  53873. */
  53874. ConeParticleEmitter.prototype.getClassName = function () {
  53875. return "ConeEmitter";
  53876. };
  53877. /**
  53878. * Serializes the particle system to a JSON object.
  53879. * @returns the JSON object
  53880. */
  53881. ConeParticleEmitter.prototype.serialize = function () {
  53882. var serializationObject = {};
  53883. serializationObject.type = this.getClassName();
  53884. serializationObject.radius = this.radius;
  53885. serializationObject.angle = this.angle;
  53886. serializationObject.directionRandomizer = this.directionRandomizer;
  53887. return serializationObject;
  53888. };
  53889. /**
  53890. * Parse properties from a JSON object
  53891. * @param serializationObject defines the JSON object
  53892. */
  53893. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  53894. this.radius = serializationObject.radius;
  53895. this.angle = serializationObject.angle;
  53896. this.directionRandomizer = serializationObject.directionRandomizer;
  53897. };
  53898. return ConeParticleEmitter;
  53899. }());
  53900. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  53901. })(BABYLON || (BABYLON = {}));
  53902. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  53903. "use strict";
  53904. var BABYLON;
  53905. (function (BABYLON) {
  53906. /**
  53907. * Particle emitter emitting particles from the inside of a sphere.
  53908. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  53909. */
  53910. var SphereParticleEmitter = /** @class */ (function () {
  53911. /**
  53912. * Creates a new instance SphereParticleEmitter
  53913. * @param radius the radius of the emission sphere (1 by default)
  53914. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  53915. */
  53916. function SphereParticleEmitter(
  53917. /**
  53918. * The radius of the emission sphere.
  53919. */
  53920. radius,
  53921. /**
  53922. * How much to randomize the particle direction [0-1].
  53923. */
  53924. directionRandomizer) {
  53925. if (radius === void 0) { radius = 1; }
  53926. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  53927. this.radius = radius;
  53928. this.directionRandomizer = directionRandomizer;
  53929. }
  53930. /**
  53931. * Called by the particle System when the direction is computed for the created particle.
  53932. * @param emitPower is the power of the particle (speed)
  53933. * @param worldMatrix is the world matrix of the particle system
  53934. * @param directionToUpdate is the direction vector to update with the result
  53935. * @param particle is the particle we are computed the direction for
  53936. */
  53937. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53938. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  53939. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53940. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53941. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53942. direction.x += randX;
  53943. direction.y += randY;
  53944. direction.z += randZ;
  53945. direction.normalize();
  53946. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  53947. };
  53948. /**
  53949. * Called by the particle System when the position is computed for the created particle.
  53950. * @param worldMatrix is the world matrix of the particle system
  53951. * @param positionToUpdate is the position vector to update with the result
  53952. * @param particle is the particle we are computed the position for
  53953. */
  53954. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53955. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  53956. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  53957. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  53958. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  53959. var randY = randRadius * Math.cos(theta);
  53960. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  53961. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53962. };
  53963. /**
  53964. * Clones the current emitter and returns a copy of it
  53965. * @returns the new emitter
  53966. */
  53967. SphereParticleEmitter.prototype.clone = function () {
  53968. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  53969. BABYLON.Tools.DeepCopy(this, newOne);
  53970. return newOne;
  53971. };
  53972. /**
  53973. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53974. * @param effect defines the update shader
  53975. */
  53976. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  53977. effect.setFloat("radius", this.radius);
  53978. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53979. };
  53980. /**
  53981. * Returns a string to use to update the GPU particles update shader
  53982. * @returns a string containng the defines string
  53983. */
  53984. SphereParticleEmitter.prototype.getEffectDefines = function () {
  53985. return "#define SPHEREEMITTER";
  53986. };
  53987. /**
  53988. * Returns the string "SphereParticleEmitter"
  53989. * @returns a string containing the class name
  53990. */
  53991. SphereParticleEmitter.prototype.getClassName = function () {
  53992. return "SphereParticleEmitter";
  53993. };
  53994. /**
  53995. * Serializes the particle system to a JSON object.
  53996. * @returns the JSON object
  53997. */
  53998. SphereParticleEmitter.prototype.serialize = function () {
  53999. var serializationObject = {};
  54000. serializationObject.type = this.getClassName();
  54001. serializationObject.radius = this.radius;
  54002. serializationObject.directionRandomizer = this.directionRandomizer;
  54003. return serializationObject;
  54004. };
  54005. /**
  54006. * Parse properties from a JSON object
  54007. * @param serializationObject defines the JSON object
  54008. */
  54009. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  54010. this.radius = serializationObject.radius;
  54011. this.directionRandomizer = serializationObject.directionRandomizer;
  54012. };
  54013. return SphereParticleEmitter;
  54014. }());
  54015. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  54016. /**
  54017. * Particle emitter emitting particles from the inside of a sphere.
  54018. * It emits the particles randomly between two vectors.
  54019. */
  54020. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  54021. __extends(SphereDirectedParticleEmitter, _super);
  54022. /**
  54023. * Creates a new instance SphereDirectedParticleEmitter
  54024. * @param radius the radius of the emission sphere (1 by default)
  54025. * @param direction1 the min limit of the emission direction (up vector by default)
  54026. * @param direction2 the max limit of the emission direction (up vector by default)
  54027. */
  54028. function SphereDirectedParticleEmitter(radius,
  54029. /**
  54030. * The min limit of the emission direction.
  54031. */
  54032. direction1,
  54033. /**
  54034. * The max limit of the emission direction.
  54035. */
  54036. direction2) {
  54037. if (radius === void 0) { radius = 1; }
  54038. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  54039. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  54040. var _this = _super.call(this, radius) || this;
  54041. _this.direction1 = direction1;
  54042. _this.direction2 = direction2;
  54043. return _this;
  54044. }
  54045. /**
  54046. * Called by the particle System when the direction is computed for the created particle.
  54047. * @param emitPower is the power of the particle (speed)
  54048. * @param worldMatrix is the world matrix of the particle system
  54049. * @param directionToUpdate is the direction vector to update with the result
  54050. * @param particle is the particle we are computed the direction for
  54051. */
  54052. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  54053. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  54054. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  54055. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  54056. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  54057. };
  54058. /**
  54059. * Clones the current emitter and returns a copy of it
  54060. * @returns the new emitter
  54061. */
  54062. SphereDirectedParticleEmitter.prototype.clone = function () {
  54063. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  54064. BABYLON.Tools.DeepCopy(this, newOne);
  54065. return newOne;
  54066. };
  54067. /**
  54068. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  54069. * @param effect defines the update shader
  54070. */
  54071. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  54072. effect.setFloat("radius", this.radius);
  54073. effect.setVector3("direction1", this.direction1);
  54074. effect.setVector3("direction2", this.direction2);
  54075. };
  54076. /**
  54077. * Returns a string to use to update the GPU particles update shader
  54078. * @returns a string containng the defines string
  54079. */
  54080. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  54081. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  54082. };
  54083. /**
  54084. * Returns the string "SphereDirectedParticleEmitter"
  54085. * @returns a string containing the class name
  54086. */
  54087. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  54088. return "SphereDirectedParticleEmitter";
  54089. };
  54090. /**
  54091. * Serializes the particle system to a JSON object.
  54092. * @returns the JSON object
  54093. */
  54094. SphereDirectedParticleEmitter.prototype.serialize = function () {
  54095. var serializationObject = _super.prototype.serialize.call(this);
  54096. ;
  54097. serializationObject.direction1 = this.direction1.asArray();
  54098. ;
  54099. serializationObject.direction2 = this.direction2.asArray();
  54100. ;
  54101. return serializationObject;
  54102. };
  54103. /**
  54104. * Parse properties from a JSON object
  54105. * @param serializationObject defines the JSON object
  54106. */
  54107. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  54108. _super.prototype.parse.call(this, serializationObject);
  54109. this.direction1.copyFrom(serializationObject.direction1);
  54110. this.direction2.copyFrom(serializationObject.direction2);
  54111. };
  54112. return SphereDirectedParticleEmitter;
  54113. }(SphereParticleEmitter));
  54114. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  54115. })(BABYLON || (BABYLON = {}));
  54116. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  54117. "use strict";
  54118. var __assign = (this && this.__assign) || Object.assign || function(t) {
  54119. for (var s, i = 1, n = arguments.length; i < n; i++) {
  54120. s = arguments[i];
  54121. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  54122. t[p] = s[p];
  54123. }
  54124. return t;
  54125. };
  54126. var BABYLON;
  54127. (function (BABYLON) {
  54128. /**
  54129. * This represents a GPU particle system in Babylon
  54130. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  54131. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  54132. */
  54133. var GPUParticleSystem = /** @class */ (function () {
  54134. /**
  54135. * Instantiates a GPU particle system.
  54136. * 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.
  54137. * @param name The name of the particle system
  54138. * @param capacity The max number of particles alive at the same time
  54139. * @param scene The scene the particle system belongs to
  54140. */
  54141. function GPUParticleSystem(name, options, scene) {
  54142. /**
  54143. * The emitter represents the Mesh or position we are attaching the particle system to.
  54144. */
  54145. this.emitter = null;
  54146. /**
  54147. * The rendering group used by the Particle system to chose when to render.
  54148. */
  54149. this.renderingGroupId = 0;
  54150. /**
  54151. * The layer mask we are rendering the particles through.
  54152. */
  54153. this.layerMask = 0x0FFFFFFF;
  54154. this._targetIndex = 0;
  54155. this._currentRenderId = -1;
  54156. this._started = false;
  54157. this._stopped = false;
  54158. this._timeDelta = 0;
  54159. this._attributesStrideSize = 14;
  54160. this._actualFrame = 0;
  54161. /**
  54162. * List of animations used by the particle system.
  54163. */
  54164. this.animations = [];
  54165. /**
  54166. * An event triggered when the system is disposed.
  54167. */
  54168. this.onDisposeObservable = new BABYLON.Observable();
  54169. /**
  54170. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54171. */
  54172. this.updateSpeed = 0.01;
  54173. /**
  54174. * The amount of time the particle system is running (depends of the overall update speed).
  54175. */
  54176. this.targetStopDuration = 0;
  54177. /**
  54178. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54179. */
  54180. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  54181. /**
  54182. * Minimum life time of emitting particles.
  54183. */
  54184. this.minLifeTime = 1;
  54185. /**
  54186. * Maximum life time of emitting particles.
  54187. */
  54188. this.maxLifeTime = 1;
  54189. /**
  54190. * Minimum Size of emitting particles.
  54191. */
  54192. this.minSize = 1;
  54193. /**
  54194. * Maximum Size of emitting particles.
  54195. */
  54196. this.maxSize = 1;
  54197. /**
  54198. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54199. */
  54200. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54201. /**
  54202. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54203. */
  54204. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54205. /**
  54206. * Color the particle will have at the end of its lifetime.
  54207. */
  54208. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  54209. /**
  54210. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  54211. */
  54212. this.emitRate = 100;
  54213. /**
  54214. * You can use gravity if you want to give an orientation to your particles.
  54215. */
  54216. this.gravity = BABYLON.Vector3.Zero();
  54217. /**
  54218. * Minimum power of emitting particles.
  54219. */
  54220. this.minEmitPower = 1;
  54221. /**
  54222. * Maximum power of emitting particles.
  54223. */
  54224. this.maxEmitPower = 1;
  54225. /**
  54226. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54227. * to override the particles.
  54228. */
  54229. this.forceDepthWrite = false;
  54230. this.id = name;
  54231. this.name = name;
  54232. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54233. this._engine = this._scene.getEngine();
  54234. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  54235. this._capacity = fullOptions.capacity;
  54236. this._activeCount = fullOptions.capacity;
  54237. this._currentActiveCount = 0;
  54238. this._scene.particleSystems.push(this);
  54239. this._updateEffectOptions = {
  54240. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  54241. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  54242. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  54243. uniformBuffersNames: [],
  54244. samplers: ["randomSampler"],
  54245. defines: "",
  54246. fallbacks: null,
  54247. onCompiled: null,
  54248. onError: null,
  54249. indexParameters: null,
  54250. maxSimultaneousLights: 0,
  54251. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  54252. };
  54253. // Random data
  54254. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  54255. var d = [];
  54256. for (var i = 0; i < maxTextureSize; ++i) {
  54257. d.push(Math.random());
  54258. d.push(Math.random());
  54259. d.push(Math.random());
  54260. d.push(Math.random());
  54261. }
  54262. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  54263. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54264. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54265. this._randomTextureSize = maxTextureSize;
  54266. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54267. }
  54268. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  54269. /**
  54270. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  54271. */
  54272. get: function () {
  54273. if (!BABYLON.Engine.LastCreatedEngine) {
  54274. return false;
  54275. }
  54276. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  54277. },
  54278. enumerable: true,
  54279. configurable: true
  54280. });
  54281. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  54282. /**
  54283. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54284. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54285. */
  54286. get: function () {
  54287. if (this.particleEmitterType.direction1) {
  54288. return this.particleEmitterType.direction1;
  54289. }
  54290. return BABYLON.Vector3.Zero();
  54291. },
  54292. set: function (value) {
  54293. if (this.particleEmitterType.direction1) {
  54294. this.particleEmitterType.direction1 = value;
  54295. }
  54296. },
  54297. enumerable: true,
  54298. configurable: true
  54299. });
  54300. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  54301. /**
  54302. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54303. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54304. */
  54305. get: function () {
  54306. if (this.particleEmitterType.direction2) {
  54307. return this.particleEmitterType.direction2;
  54308. }
  54309. return BABYLON.Vector3.Zero();
  54310. },
  54311. set: function (value) {
  54312. if (this.particleEmitterType.direction2) {
  54313. this.particleEmitterType.direction2 = value;
  54314. }
  54315. },
  54316. enumerable: true,
  54317. configurable: true
  54318. });
  54319. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  54320. /**
  54321. * 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.
  54322. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54323. */
  54324. get: function () {
  54325. if (this.particleEmitterType.minEmitBox) {
  54326. return this.particleEmitterType.minEmitBox;
  54327. }
  54328. return BABYLON.Vector3.Zero();
  54329. },
  54330. set: function (value) {
  54331. if (this.particleEmitterType.minEmitBox) {
  54332. this.particleEmitterType.minEmitBox = value;
  54333. }
  54334. },
  54335. enumerable: true,
  54336. configurable: true
  54337. });
  54338. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  54339. /**
  54340. * 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.
  54341. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54342. */
  54343. get: function () {
  54344. if (this.particleEmitterType.maxEmitBox) {
  54345. return this.particleEmitterType.maxEmitBox;
  54346. }
  54347. return BABYLON.Vector3.Zero();
  54348. },
  54349. set: function (value) {
  54350. if (this.particleEmitterType.maxEmitBox) {
  54351. this.particleEmitterType.maxEmitBox = value;
  54352. }
  54353. },
  54354. enumerable: true,
  54355. configurable: true
  54356. });
  54357. /**
  54358. * Gets the maximum number of particles active at the same time.
  54359. * @returns The max number of active particles.
  54360. */
  54361. GPUParticleSystem.prototype.getCapacity = function () {
  54362. return this._capacity;
  54363. };
  54364. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  54365. /**
  54366. * Gets or set the number of active particles
  54367. */
  54368. get: function () {
  54369. return this._activeCount;
  54370. },
  54371. set: function (value) {
  54372. this._activeCount = Math.min(value, this._capacity);
  54373. },
  54374. enumerable: true,
  54375. configurable: true
  54376. });
  54377. /**
  54378. * Is this system ready to be used/rendered
  54379. * @return true if the system is ready
  54380. */
  54381. GPUParticleSystem.prototype.isReady = function () {
  54382. if (!this._updateEffect) {
  54383. this._recreateUpdateEffect();
  54384. this._recreateRenderEffect();
  54385. return false;
  54386. }
  54387. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  54388. return false;
  54389. }
  54390. return true;
  54391. };
  54392. /**
  54393. * Gets Wether the system has been started.
  54394. * @returns True if it has been started, otherwise false.
  54395. */
  54396. GPUParticleSystem.prototype.isStarted = function () {
  54397. return this._started;
  54398. };
  54399. /**
  54400. * Starts the particle system and begins to emit.
  54401. */
  54402. GPUParticleSystem.prototype.start = function () {
  54403. this._started = true;
  54404. this._stopped = false;
  54405. };
  54406. /**
  54407. * Stops the particle system.
  54408. */
  54409. GPUParticleSystem.prototype.stop = function () {
  54410. this._stopped = true;
  54411. };
  54412. /**
  54413. * Remove all active particles
  54414. */
  54415. GPUParticleSystem.prototype.reset = function () {
  54416. this._releaseBuffers();
  54417. this._releaseVAOs();
  54418. this._currentActiveCount = 0;
  54419. this._targetIndex = 0;
  54420. };
  54421. /**
  54422. * Returns the string "GPUParticleSystem"
  54423. * @returns a string containing the class name
  54424. */
  54425. GPUParticleSystem.prototype.getClassName = function () {
  54426. return "GPUParticleSystem";
  54427. };
  54428. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  54429. var updateVertexBuffers = {};
  54430. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  54431. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  54432. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  54433. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  54434. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  54435. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  54436. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  54437. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  54438. this._engine.bindArrayBuffer(null);
  54439. return vao;
  54440. };
  54441. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  54442. var renderVertexBuffers = {};
  54443. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  54444. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  54445. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  54446. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  54447. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  54448. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  54449. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  54450. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  54451. this._engine.bindArrayBuffer(null);
  54452. return vao;
  54453. };
  54454. GPUParticleSystem.prototype._initialize = function (force) {
  54455. if (force === void 0) { force = false; }
  54456. if (this._buffer0 && !force) {
  54457. return;
  54458. }
  54459. var engine = this._scene.getEngine();
  54460. var data = new Array();
  54461. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  54462. // position
  54463. data.push(0.0);
  54464. data.push(0.0);
  54465. data.push(0.0);
  54466. // Age and life
  54467. data.push(0.0); // create the particle as a dead one to create a new one at start
  54468. data.push(0.0);
  54469. // Seed
  54470. data.push(Math.random());
  54471. // Size
  54472. data.push(0.0);
  54473. // color
  54474. data.push(0.0);
  54475. data.push(0.0);
  54476. data.push(0.0);
  54477. data.push(0.0);
  54478. // direction
  54479. data.push(0.0);
  54480. data.push(0.0);
  54481. data.push(0.0);
  54482. }
  54483. // Sprite data
  54484. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  54485. -0.5, 0.5, 0, 1,
  54486. -0.5, -0.5, 0, 0,
  54487. 0.5, -0.5, 1, 0]);
  54488. // Buffers
  54489. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  54490. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  54491. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  54492. // Update VAO
  54493. this._updateVAO = [];
  54494. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  54495. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  54496. // Render VAO
  54497. this._renderVAO = [];
  54498. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  54499. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  54500. // Links
  54501. this._sourceBuffer = this._buffer0;
  54502. this._targetBuffer = this._buffer1;
  54503. };
  54504. /** @ignore */
  54505. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  54506. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  54507. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  54508. return;
  54509. }
  54510. this._updateEffectOptions.defines = defines;
  54511. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  54512. };
  54513. /** @ignore */
  54514. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  54515. var defines = "";
  54516. if (this._scene.clipPlane) {
  54517. defines = "\n#define CLIPPLANE";
  54518. }
  54519. if (this._renderEffect && this._renderEffect.defines === defines) {
  54520. return;
  54521. }
  54522. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  54523. };
  54524. /**
  54525. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  54526. */
  54527. GPUParticleSystem.prototype.animate = function () {
  54528. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  54529. this._actualFrame += this._timeDelta;
  54530. if (!this._stopped) {
  54531. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  54532. this.stop();
  54533. }
  54534. }
  54535. };
  54536. /**
  54537. * Renders the particle system in its current state.
  54538. * @returns the current number of particles
  54539. */
  54540. GPUParticleSystem.prototype.render = function () {
  54541. if (!this._started) {
  54542. return 0;
  54543. }
  54544. this._recreateUpdateEffect();
  54545. this._recreateRenderEffect();
  54546. if (!this.isReady()) {
  54547. return 0;
  54548. }
  54549. if (this._currentRenderId === this._scene.getRenderId()) {
  54550. return 0;
  54551. }
  54552. this._currentRenderId = this._scene.getRenderId();
  54553. // Get everything ready to render
  54554. this._initialize();
  54555. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  54556. // Enable update effect
  54557. this._engine.enableEffect(this._updateEffect);
  54558. this._engine.setState(false);
  54559. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  54560. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  54561. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  54562. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  54563. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  54564. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  54565. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  54566. this._updateEffect.setDirectColor4("color1", this.color1);
  54567. this._updateEffect.setDirectColor4("color2", this.color2);
  54568. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  54569. this._updateEffect.setVector3("gravity", this.gravity);
  54570. if (this.particleEmitterType) {
  54571. this.particleEmitterType.applyToShader(this._updateEffect);
  54572. }
  54573. var emitterWM;
  54574. if (this.emitter.position) {
  54575. var emitterMesh = this.emitter;
  54576. emitterWM = emitterMesh.getWorldMatrix();
  54577. }
  54578. else {
  54579. var emitterPosition = this.emitter;
  54580. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  54581. }
  54582. this._updateEffect.setMatrix("emitterWM", emitterWM);
  54583. // Bind source VAO
  54584. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  54585. // Update
  54586. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  54587. this._engine.setRasterizerState(false);
  54588. this._engine.beginTransformFeedback();
  54589. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  54590. this._engine.endTransformFeedback();
  54591. this._engine.setRasterizerState(true);
  54592. this._engine.bindTransformFeedbackBuffer(null);
  54593. // Enable render effect
  54594. this._engine.enableEffect(this._renderEffect);
  54595. var viewMatrix = this._scene.getViewMatrix();
  54596. this._renderEffect.setMatrix("view", viewMatrix);
  54597. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  54598. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  54599. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  54600. if (this._scene.clipPlane) {
  54601. var clipPlane = this._scene.clipPlane;
  54602. var invView = viewMatrix.clone();
  54603. invView.invert();
  54604. this._renderEffect.setMatrix("invView", invView);
  54605. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  54606. }
  54607. // Draw order
  54608. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  54609. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  54610. }
  54611. else {
  54612. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54613. }
  54614. if (this.forceDepthWrite) {
  54615. this._engine.setDepthWrite(true);
  54616. }
  54617. // Bind source VAO
  54618. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  54619. // Render
  54620. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  54621. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54622. // Switch VAOs
  54623. this._targetIndex++;
  54624. if (this._targetIndex === 2) {
  54625. this._targetIndex = 0;
  54626. }
  54627. // Switch buffers
  54628. var tmpBuffer = this._sourceBuffer;
  54629. this._sourceBuffer = this._targetBuffer;
  54630. this._targetBuffer = tmpBuffer;
  54631. return this._currentActiveCount;
  54632. };
  54633. /**
  54634. * Rebuilds the particle system
  54635. */
  54636. GPUParticleSystem.prototype.rebuild = function () {
  54637. this._initialize(true);
  54638. };
  54639. GPUParticleSystem.prototype._releaseBuffers = function () {
  54640. if (this._buffer0) {
  54641. this._buffer0.dispose();
  54642. this._buffer0 = null;
  54643. }
  54644. if (this._buffer1) {
  54645. this._buffer1.dispose();
  54646. this._buffer1 = null;
  54647. }
  54648. if (this._spriteBuffer) {
  54649. this._spriteBuffer.dispose();
  54650. this._spriteBuffer = null;
  54651. }
  54652. };
  54653. GPUParticleSystem.prototype._releaseVAOs = function () {
  54654. if (!this._updateVAO) {
  54655. return;
  54656. }
  54657. for (var index = 0; index < this._updateVAO.length; index++) {
  54658. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  54659. }
  54660. this._updateVAO = [];
  54661. for (var index = 0; index < this._renderVAO.length; index++) {
  54662. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  54663. }
  54664. this._renderVAO = [];
  54665. };
  54666. /**
  54667. * Disposes the particle system and free the associated resources
  54668. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  54669. */
  54670. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  54671. if (disposeTexture === void 0) { disposeTexture = true; }
  54672. var index = this._scene.particleSystems.indexOf(this);
  54673. if (index > -1) {
  54674. this._scene.particleSystems.splice(index, 1);
  54675. }
  54676. this._releaseBuffers();
  54677. this._releaseVAOs();
  54678. if (this._randomTexture) {
  54679. this._randomTexture.dispose();
  54680. this._randomTexture = null;
  54681. }
  54682. if (disposeTexture && this.particleTexture) {
  54683. this.particleTexture.dispose();
  54684. this.particleTexture = null;
  54685. }
  54686. // Callback
  54687. this.onDisposeObservable.notifyObservers(this);
  54688. this.onDisposeObservable.clear();
  54689. };
  54690. /**
  54691. * Clones the particle system.
  54692. * @param name The name of the cloned object
  54693. * @param newEmitter The new emitter to use
  54694. * @returns the cloned particle system
  54695. */
  54696. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  54697. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  54698. BABYLON.Tools.DeepCopy(this, result);
  54699. if (newEmitter === undefined) {
  54700. newEmitter = this.emitter;
  54701. }
  54702. result.emitter = newEmitter;
  54703. if (this.particleTexture) {
  54704. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  54705. }
  54706. return result;
  54707. };
  54708. /**
  54709. * Serializes the particle system to a JSON object.
  54710. * @returns the JSON object
  54711. */
  54712. GPUParticleSystem.prototype.serialize = function () {
  54713. var serializationObject = {};
  54714. serializationObject.name = this.name;
  54715. serializationObject.id = this.id;
  54716. // Emitter
  54717. if (this.emitter.position) {
  54718. var emitterMesh = this.emitter;
  54719. serializationObject.emitterId = emitterMesh.id;
  54720. }
  54721. else {
  54722. var emitterPosition = this.emitter;
  54723. serializationObject.emitter = emitterPosition.asArray();
  54724. }
  54725. serializationObject.capacity = this.getCapacity();
  54726. if (this.particleTexture) {
  54727. serializationObject.textureName = this.particleTexture.name;
  54728. }
  54729. // Animations
  54730. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  54731. // Particle system
  54732. serializationObject.activeParticleCount = this.activeParticleCount;
  54733. serializationObject.randomTextureSize = this._randomTextureSize;
  54734. serializationObject.minSize = this.minSize;
  54735. serializationObject.maxSize = this.maxSize;
  54736. serializationObject.minEmitPower = this.minEmitPower;
  54737. serializationObject.maxEmitPower = this.maxEmitPower;
  54738. serializationObject.minLifeTime = this.minLifeTime;
  54739. serializationObject.maxLifeTime = this.maxLifeTime;
  54740. serializationObject.emitRate = this.emitRate;
  54741. serializationObject.gravity = this.gravity.asArray();
  54742. serializationObject.color1 = this.color1.asArray();
  54743. serializationObject.color2 = this.color2.asArray();
  54744. serializationObject.colorDead = this.colorDead.asArray();
  54745. serializationObject.updateSpeed = this.updateSpeed;
  54746. serializationObject.targetStopDuration = this.targetStopDuration;
  54747. serializationObject.blendMode = this.blendMode;
  54748. // Emitter
  54749. if (this.particleEmitterType) {
  54750. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  54751. }
  54752. return serializationObject;
  54753. };
  54754. /**
  54755. * Parses a JSON object to create a GPU particle system.
  54756. * @param parsedParticleSystem The JSON object to parse
  54757. * @param scene The scene to create the particle system in
  54758. * @param rootUrl The root url to use to load external dependencies like texture
  54759. * @returns the parsed GPU particle system
  54760. */
  54761. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  54762. var name = parsedParticleSystem.name;
  54763. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  54764. if (parsedParticleSystem.id) {
  54765. particleSystem.id = parsedParticleSystem.id;
  54766. }
  54767. // Texture
  54768. if (parsedParticleSystem.textureName) {
  54769. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  54770. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  54771. }
  54772. // Emitter
  54773. if (parsedParticleSystem.emitterId) {
  54774. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  54775. }
  54776. else {
  54777. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  54778. }
  54779. // Animations
  54780. if (parsedParticleSystem.animations) {
  54781. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  54782. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  54783. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54784. }
  54785. }
  54786. // Particle system
  54787. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  54788. particleSystem.minSize = parsedParticleSystem.minSize;
  54789. particleSystem.maxSize = parsedParticleSystem.maxSize;
  54790. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  54791. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  54792. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  54793. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  54794. particleSystem.emitRate = parsedParticleSystem.emitRate;
  54795. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  54796. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  54797. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  54798. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  54799. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  54800. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  54801. particleSystem.blendMode = parsedParticleSystem.blendMode;
  54802. // Emitter
  54803. if (parsedParticleSystem.particleEmitterType) {
  54804. var emitterType = void 0;
  54805. switch (parsedParticleSystem.particleEmitterType.type) {
  54806. case "SphereEmitter":
  54807. emitterType = new BABYLON.SphereParticleEmitter();
  54808. break;
  54809. case "SphereDirectedParticleEmitter":
  54810. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  54811. break;
  54812. case "ConeEmitter":
  54813. emitterType = new BABYLON.ConeParticleEmitter();
  54814. break;
  54815. case "BoxEmitter":
  54816. default:
  54817. emitterType = new BABYLON.BoxParticleEmitter();
  54818. break;
  54819. }
  54820. emitterType.parse(parsedParticleSystem.particleEmitterType);
  54821. particleSystem.particleEmitterType = emitterType;
  54822. }
  54823. return particleSystem;
  54824. };
  54825. return GPUParticleSystem;
  54826. }());
  54827. BABYLON.GPUParticleSystem = GPUParticleSystem;
  54828. })(BABYLON || (BABYLON = {}));
  54829. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  54830. "use strict";
  54831. var BABYLON;
  54832. (function (BABYLON) {
  54833. /**
  54834. * Represents one particle of a solid particle system.
  54835. */
  54836. var SolidParticle = /** @class */ (function () {
  54837. /**
  54838. * Creates a Solid Particle object.
  54839. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  54840. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  54841. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  54842. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  54843. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  54844. * @param shapeId (integer) is the model shape identifier in the SPS.
  54845. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  54846. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  54847. */
  54848. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  54849. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  54850. /**
  54851. * particle global index
  54852. */
  54853. this.idx = 0;
  54854. /**
  54855. * The color of the particle
  54856. */
  54857. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54858. /**
  54859. * The world space position of the particle.
  54860. */
  54861. this.position = BABYLON.Vector3.Zero();
  54862. /**
  54863. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  54864. */
  54865. this.rotation = BABYLON.Vector3.Zero();
  54866. /**
  54867. * The scaling of the particle.
  54868. */
  54869. this.scaling = BABYLON.Vector3.One();
  54870. /**
  54871. * The uvs of the particle.
  54872. */
  54873. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  54874. /**
  54875. * The current speed of the particle.
  54876. */
  54877. this.velocity = BABYLON.Vector3.Zero();
  54878. /**
  54879. * The pivot point in the particle local space.
  54880. */
  54881. this.pivot = BABYLON.Vector3.Zero();
  54882. /**
  54883. * Must the particle be translated from its pivot point in its local space ?
  54884. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  54885. * Default : false
  54886. */
  54887. this.translateFromPivot = false;
  54888. /**
  54889. * Is the particle active or not ?
  54890. */
  54891. this.alive = true;
  54892. /**
  54893. * Is the particle visible or not ?
  54894. */
  54895. this.isVisible = true;
  54896. /**
  54897. * Index of this particle in the global "positions" array (Internal use)
  54898. */
  54899. this._pos = 0;
  54900. /**
  54901. * Index of this particle in the global "indices" array (Internal use)
  54902. */
  54903. this._ind = 0;
  54904. /**
  54905. * ModelShape id of this particle
  54906. */
  54907. this.shapeId = 0;
  54908. /**
  54909. * Index of the particle in its shape id (Internal use)
  54910. */
  54911. this.idxInShape = 0;
  54912. /**
  54913. * Still set as invisible in order to skip useless computations (Internal use)
  54914. */
  54915. this._stillInvisible = false;
  54916. /**
  54917. * Last computed particle rotation matrix
  54918. */
  54919. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  54920. /**
  54921. * Parent particle Id, if any.
  54922. * Default null.
  54923. */
  54924. this.parentId = null;
  54925. /**
  54926. * Internal global position in the SPS.
  54927. */
  54928. this._globalPosition = BABYLON.Vector3.Zero();
  54929. this.idx = particleIndex;
  54930. this._pos = positionIndex;
  54931. this._ind = indiceIndex;
  54932. this._model = model;
  54933. this.shapeId = shapeId;
  54934. this.idxInShape = idxInShape;
  54935. this._sps = sps;
  54936. if (modelBoundingInfo) {
  54937. this._modelBoundingInfo = modelBoundingInfo;
  54938. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  54939. }
  54940. }
  54941. Object.defineProperty(SolidParticle.prototype, "scale", {
  54942. /**
  54943. * Legacy support, changed scale to scaling
  54944. */
  54945. get: function () {
  54946. return this.scaling;
  54947. },
  54948. /**
  54949. * Legacy support, changed scale to scaling
  54950. */
  54951. set: function (scale) {
  54952. this.scaling = scale;
  54953. },
  54954. enumerable: true,
  54955. configurable: true
  54956. });
  54957. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54958. /**
  54959. * Legacy support, changed quaternion to rotationQuaternion
  54960. */
  54961. get: function () {
  54962. return this.rotationQuaternion;
  54963. },
  54964. /**
  54965. * Legacy support, changed quaternion to rotationQuaternion
  54966. */
  54967. set: function (q) {
  54968. this.rotationQuaternion = q;
  54969. },
  54970. enumerable: true,
  54971. configurable: true
  54972. });
  54973. /**
  54974. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54975. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54976. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  54977. * @returns true if it intersects
  54978. */
  54979. SolidParticle.prototype.intersectsMesh = function (target) {
  54980. if (!this._boundingInfo || !target._boundingInfo) {
  54981. return false;
  54982. }
  54983. if (this._sps._bSphereOnly) {
  54984. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54985. }
  54986. return this._boundingInfo.intersects(target._boundingInfo, false);
  54987. };
  54988. return SolidParticle;
  54989. }());
  54990. BABYLON.SolidParticle = SolidParticle;
  54991. /**
  54992. * Represents the shape of the model used by one particle of a solid particle system.
  54993. * SPS internal tool, don't use it manually.
  54994. */
  54995. var ModelShape = /** @class */ (function () {
  54996. /**
  54997. * 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.
  54998. * SPS internal tool, don't use it manually.
  54999. * @ignore
  55000. */
  55001. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  55002. /**
  55003. * length of the shape in the model indices array (internal use)
  55004. */
  55005. this._indicesLength = 0;
  55006. this.shapeID = id;
  55007. this._shape = shape;
  55008. this._indicesLength = indicesLength;
  55009. this._shapeUV = shapeUV;
  55010. this._positionFunction = posFunction;
  55011. this._vertexFunction = vtxFunction;
  55012. }
  55013. return ModelShape;
  55014. }());
  55015. BABYLON.ModelShape = ModelShape;
  55016. /**
  55017. * Represents a Depth Sorted Particle in the solid particle system.
  55018. */
  55019. var DepthSortedParticle = /** @class */ (function () {
  55020. function DepthSortedParticle() {
  55021. /**
  55022. * Index of the particle in the "indices" array
  55023. */
  55024. this.ind = 0;
  55025. /**
  55026. * Length of the particle shape in the "indices" array
  55027. */
  55028. this.indicesLength = 0;
  55029. /**
  55030. * Squared distance from the particle to the camera
  55031. */
  55032. this.sqDistance = 0.0;
  55033. }
  55034. return DepthSortedParticle;
  55035. }());
  55036. BABYLON.DepthSortedParticle = DepthSortedParticle;
  55037. })(BABYLON || (BABYLON = {}));
  55038. //# sourceMappingURL=babylon.solidParticle.js.map
  55039. "use strict";
  55040. var BABYLON;
  55041. (function (BABYLON) {
  55042. /**
  55043. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  55044. *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.
  55045. * The SPS is also a particle system. It provides some methods to manage the particles.
  55046. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  55047. *
  55048. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  55049. */
  55050. var SolidParticleSystem = /** @class */ (function () {
  55051. /**
  55052. * Creates a SPS (Solid Particle System) object.
  55053. * @param name (String) is the SPS name, this will be the underlying mesh name.
  55054. * @param scene (Scene) is the scene in which the SPS is added.
  55055. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  55056. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  55057. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  55058. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  55059. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  55060. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  55061. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  55062. */
  55063. function SolidParticleSystem(name, scene, options) {
  55064. /**
  55065. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  55066. * Example : var p = SPS.particles[i];
  55067. */
  55068. this.particles = new Array();
  55069. /**
  55070. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  55071. */
  55072. this.nbParticles = 0;
  55073. /**
  55074. * If the particles must ever face the camera (default false). Useful for planar particles.
  55075. */
  55076. this.billboard = false;
  55077. /**
  55078. * Recompute normals when adding a shape
  55079. */
  55080. this.recomputeNormals = true;
  55081. /**
  55082. * This a counter ofr your own usage. It's not set by any SPS functions.
  55083. */
  55084. this.counter = 0;
  55085. /**
  55086. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  55087. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  55088. */
  55089. this.vars = {};
  55090. /**
  55091. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  55092. */
  55093. this._bSphereOnly = false;
  55094. /**
  55095. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  55096. */
  55097. this._bSphereRadiusFactor = 1.0;
  55098. this._positions = new Array();
  55099. this._indices = new Array();
  55100. this._normals = new Array();
  55101. this._colors = new Array();
  55102. this._uvs = new Array();
  55103. this._index = 0; // indices index
  55104. this._updatable = true;
  55105. this._pickable = false;
  55106. this._isVisibilityBoxLocked = false;
  55107. this._alwaysVisible = false;
  55108. this._depthSort = false;
  55109. this._shapeCounter = 0;
  55110. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  55111. this._color = new BABYLON.Color4(0, 0, 0, 0);
  55112. this._computeParticleColor = true;
  55113. this._computeParticleTexture = true;
  55114. this._computeParticleRotation = true;
  55115. this._computeParticleVertex = false;
  55116. this._computeBoundingBox = false;
  55117. this._depthSortParticles = true;
  55118. this._cam_axisZ = BABYLON.Vector3.Zero();
  55119. this._cam_axisY = BABYLON.Vector3.Zero();
  55120. this._cam_axisX = BABYLON.Vector3.Zero();
  55121. this._axisZ = BABYLON.Axis.Z;
  55122. this._camDir = BABYLON.Vector3.Zero();
  55123. this._camInvertedPosition = BABYLON.Vector3.Zero();
  55124. this._rotMatrix = new BABYLON.Matrix();
  55125. this._invertMatrix = new BABYLON.Matrix();
  55126. this._rotated = BABYLON.Vector3.Zero();
  55127. this._quaternion = new BABYLON.Quaternion();
  55128. this._vertex = BABYLON.Vector3.Zero();
  55129. this._normal = BABYLON.Vector3.Zero();
  55130. this._yaw = 0.0;
  55131. this._pitch = 0.0;
  55132. this._roll = 0.0;
  55133. this._halfroll = 0.0;
  55134. this._halfpitch = 0.0;
  55135. this._halfyaw = 0.0;
  55136. this._sinRoll = 0.0;
  55137. this._cosRoll = 0.0;
  55138. this._sinPitch = 0.0;
  55139. this._cosPitch = 0.0;
  55140. this._sinYaw = 0.0;
  55141. this._cosYaw = 0.0;
  55142. this._mustUnrotateFixedNormals = false;
  55143. this._minimum = BABYLON.Vector3.Zero();
  55144. this._maximum = BABYLON.Vector3.Zero();
  55145. this._minBbox = BABYLON.Vector3.Zero();
  55146. this._maxBbox = BABYLON.Vector3.Zero();
  55147. this._particlesIntersect = false;
  55148. this._depthSortFunction = function (p1, p2) {
  55149. return (p2.sqDistance - p1.sqDistance);
  55150. };
  55151. this._needs32Bits = false;
  55152. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  55153. this._scaledPivot = BABYLON.Vector3.Zero();
  55154. this._particleHasParent = false;
  55155. this.name = name;
  55156. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55157. this._camera = scene.activeCamera;
  55158. this._pickable = options ? options.isPickable : false;
  55159. this._depthSort = options ? options.enableDepthSort : false;
  55160. this._particlesIntersect = options ? options.particleIntersection : false;
  55161. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  55162. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  55163. if (options && options.updatable) {
  55164. this._updatable = options.updatable;
  55165. }
  55166. else {
  55167. this._updatable = true;
  55168. }
  55169. if (this._pickable) {
  55170. this.pickedParticles = [];
  55171. }
  55172. if (this._depthSort) {
  55173. this.depthSortedParticles = [];
  55174. }
  55175. }
  55176. /**
  55177. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55178. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55179. * @returns the created mesh
  55180. */
  55181. SolidParticleSystem.prototype.buildMesh = function () {
  55182. if (this.nbParticles === 0) {
  55183. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55184. this.addShape(triangle, 1);
  55185. triangle.dispose();
  55186. }
  55187. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  55188. this._positions32 = new Float32Array(this._positions);
  55189. this._uvs32 = new Float32Array(this._uvs);
  55190. this._colors32 = new Float32Array(this._colors);
  55191. if (this.recomputeNormals) {
  55192. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  55193. }
  55194. this._normals32 = new Float32Array(this._normals);
  55195. this._fixedNormal32 = new Float32Array(this._normals);
  55196. if (this._mustUnrotateFixedNormals) {
  55197. this._unrotateFixedNormals();
  55198. }
  55199. var vertexData = new BABYLON.VertexData();
  55200. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  55201. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  55202. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  55203. if (this._uvs32) {
  55204. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  55205. ;
  55206. }
  55207. if (this._colors32) {
  55208. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  55209. }
  55210. var mesh = new BABYLON.Mesh(this.name, this._scene);
  55211. vertexData.applyToMesh(mesh, this._updatable);
  55212. this.mesh = mesh;
  55213. this.mesh.isPickable = this._pickable;
  55214. // free memory
  55215. if (!this._depthSort) {
  55216. this._indices = null;
  55217. }
  55218. this._positions = null;
  55219. this._normals = null;
  55220. this._uvs = null;
  55221. this._colors = null;
  55222. if (!this._updatable) {
  55223. this.particles.length = 0;
  55224. }
  55225. return mesh;
  55226. };
  55227. /**
  55228. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  55229. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  55230. * Thus the particles generated from `digest()` have their property `position` set yet.
  55231. * @param mesh ( Mesh ) is the mesh to be digested
  55232. * @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
  55233. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55234. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55235. * @returns the current SPS
  55236. */
  55237. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55238. var size = (options && options.facetNb) || 1;
  55239. var number = (options && options.number) || 0;
  55240. var delta = (options && options.delta) || 0;
  55241. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55242. var meshInd = mesh.getIndices();
  55243. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55244. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55245. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55246. var f = 0; // facet counter
  55247. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55248. // compute size from number
  55249. if (number) {
  55250. number = (number > totalFacets) ? totalFacets : number;
  55251. size = Math.round(totalFacets / number);
  55252. delta = 0;
  55253. }
  55254. else {
  55255. size = (size > totalFacets) ? totalFacets : size;
  55256. }
  55257. var facetPos = []; // submesh positions
  55258. var facetInd = []; // submesh indices
  55259. var facetUV = []; // submesh UV
  55260. var facetCol = []; // submesh colors
  55261. var barycenter = BABYLON.Vector3.Zero();
  55262. var sizeO = size;
  55263. while (f < totalFacets) {
  55264. size = sizeO + Math.floor((1 + delta) * Math.random());
  55265. if (f > totalFacets - size) {
  55266. size = totalFacets - f;
  55267. }
  55268. // reset temp arrays
  55269. facetPos.length = 0;
  55270. facetInd.length = 0;
  55271. facetUV.length = 0;
  55272. facetCol.length = 0;
  55273. // iterate over "size" facets
  55274. var fi = 0;
  55275. for (var j = f * 3; j < (f + size) * 3; j++) {
  55276. facetInd.push(fi);
  55277. var i = meshInd[j];
  55278. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55279. if (meshUV) {
  55280. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55281. }
  55282. if (meshCol) {
  55283. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55284. }
  55285. fi++;
  55286. }
  55287. // create a model shape for each single particle
  55288. var idx = this.nbParticles;
  55289. var shape = this._posToShape(facetPos);
  55290. var shapeUV = this._uvsToShapeUV(facetUV);
  55291. // compute the barycenter of the shape
  55292. var v;
  55293. for (v = 0; v < shape.length; v++) {
  55294. barycenter.addInPlace(shape[v]);
  55295. }
  55296. barycenter.scaleInPlace(1 / shape.length);
  55297. // shift the shape from its barycenter to the origin
  55298. for (v = 0; v < shape.length; v++) {
  55299. shape[v].subtractInPlace(barycenter);
  55300. }
  55301. var bInfo;
  55302. if (this._particlesIntersect) {
  55303. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  55304. }
  55305. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  55306. // add the particle in the SPS
  55307. var currentPos = this._positions.length;
  55308. var currentInd = this._indices.length;
  55309. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  55310. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  55311. // initialize the particle position
  55312. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55313. this._index += shape.length;
  55314. idx++;
  55315. this.nbParticles++;
  55316. this._shapeCounter++;
  55317. f += size;
  55318. }
  55319. return this;
  55320. };
  55321. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  55322. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  55323. var index = 0;
  55324. var idx = 0;
  55325. for (var p = 0; p < this.particles.length; p++) {
  55326. this._particle = this.particles[p];
  55327. this._shape = this._particle._model._shape;
  55328. if (this._particle.rotationQuaternion) {
  55329. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55330. }
  55331. else {
  55332. this._yaw = this._particle.rotation.y;
  55333. this._pitch = this._particle.rotation.x;
  55334. this._roll = this._particle.rotation.z;
  55335. this._quaternionRotationYPR();
  55336. }
  55337. this._quaternionToRotationMatrix();
  55338. this._rotMatrix.invertToRef(this._invertMatrix);
  55339. for (var pt = 0; pt < this._shape.length; pt++) {
  55340. idx = index + pt * 3;
  55341. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  55342. this._fixedNormal32[idx] = this._normal.x;
  55343. this._fixedNormal32[idx + 1] = this._normal.y;
  55344. this._fixedNormal32[idx + 2] = this._normal.z;
  55345. }
  55346. index = idx + 3;
  55347. }
  55348. };
  55349. //reset copy
  55350. SolidParticleSystem.prototype._resetCopy = function () {
  55351. this._copy.position.x = 0;
  55352. this._copy.position.y = 0;
  55353. this._copy.position.z = 0;
  55354. this._copy.rotation.x = 0;
  55355. this._copy.rotation.y = 0;
  55356. this._copy.rotation.z = 0;
  55357. this._copy.rotationQuaternion = null;
  55358. this._copy.scaling.x = 1.0;
  55359. this._copy.scaling.y = 1.0;
  55360. this._copy.scaling.z = 1.0;
  55361. this._copy.uvs.x = 0;
  55362. this._copy.uvs.y = 0;
  55363. this._copy.uvs.z = 1.0;
  55364. this._copy.uvs.w = 1.0;
  55365. this._copy.color = null;
  55366. this._copy.translateFromPivot = false;
  55367. };
  55368. // _meshBuilder : inserts the shape model in the global SPS mesh
  55369. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  55370. var i;
  55371. var u = 0;
  55372. var c = 0;
  55373. var n = 0;
  55374. this._resetCopy();
  55375. if (options && options.positionFunction) {
  55376. options.positionFunction(this._copy, idx, idxInShape);
  55377. this._mustUnrotateFixedNormals = true;
  55378. }
  55379. if (this._copy.rotationQuaternion) {
  55380. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55381. }
  55382. else {
  55383. this._yaw = this._copy.rotation.y;
  55384. this._pitch = this._copy.rotation.x;
  55385. this._roll = this._copy.rotation.z;
  55386. this._quaternionRotationYPR();
  55387. }
  55388. this._quaternionToRotationMatrix();
  55389. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  55390. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  55391. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  55392. if (this._copy.translateFromPivot) {
  55393. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  55394. }
  55395. else {
  55396. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  55397. }
  55398. for (i = 0; i < shape.length; i++) {
  55399. this._vertex.x = shape[i].x;
  55400. this._vertex.y = shape[i].y;
  55401. this._vertex.z = shape[i].z;
  55402. if (options && options.vertexFunction) {
  55403. options.vertexFunction(this._copy, this._vertex, i);
  55404. }
  55405. this._vertex.x *= this._copy.scaling.x;
  55406. this._vertex.y *= this._copy.scaling.y;
  55407. this._vertex.z *= this._copy.scaling.z;
  55408. this._vertex.x -= this._scaledPivot.x;
  55409. this._vertex.y -= this._scaledPivot.y;
  55410. this._vertex.z -= this._scaledPivot.z;
  55411. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55412. this._rotated.addInPlace(this._pivotBackTranslation);
  55413. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55414. if (meshUV) {
  55415. 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);
  55416. u += 2;
  55417. }
  55418. if (this._copy.color) {
  55419. this._color = this._copy.color;
  55420. }
  55421. else if (meshCol && meshCol[c] !== undefined) {
  55422. this._color.r = meshCol[c];
  55423. this._color.g = meshCol[c + 1];
  55424. this._color.b = meshCol[c + 2];
  55425. this._color.a = meshCol[c + 3];
  55426. }
  55427. else {
  55428. this._color.r = 1.0;
  55429. this._color.g = 1.0;
  55430. this._color.b = 1.0;
  55431. this._color.a = 1.0;
  55432. }
  55433. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55434. c += 4;
  55435. if (!this.recomputeNormals && meshNor) {
  55436. this._normal.x = meshNor[n];
  55437. this._normal.y = meshNor[n + 1];
  55438. this._normal.z = meshNor[n + 2];
  55439. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  55440. normals.push(this._normal.x, this._normal.y, this._normal.z);
  55441. n += 3;
  55442. }
  55443. }
  55444. for (i = 0; i < meshInd.length; i++) {
  55445. var current_ind = p + meshInd[i];
  55446. indices.push(current_ind);
  55447. if (current_ind > 65535) {
  55448. this._needs32Bits = true;
  55449. }
  55450. }
  55451. if (this._pickable) {
  55452. var nbfaces = meshInd.length / 3;
  55453. for (i = 0; i < nbfaces; i++) {
  55454. this.pickedParticles.push({ idx: idx, faceId: i });
  55455. }
  55456. }
  55457. if (this._depthSort) {
  55458. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  55459. }
  55460. return this._copy;
  55461. };
  55462. // returns a shape array from positions array
  55463. SolidParticleSystem.prototype._posToShape = function (positions) {
  55464. var shape = [];
  55465. for (var i = 0; i < positions.length; i += 3) {
  55466. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55467. }
  55468. return shape;
  55469. };
  55470. // returns a shapeUV array from a Vector4 uvs
  55471. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55472. var shapeUV = [];
  55473. if (uvs) {
  55474. for (var i = 0; i < uvs.length; i++)
  55475. shapeUV.push(uvs[i]);
  55476. }
  55477. return shapeUV;
  55478. };
  55479. // adds a new particle object in the particles array
  55480. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  55481. if (bInfo === void 0) { bInfo = null; }
  55482. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  55483. this.particles.push(sp);
  55484. return sp;
  55485. };
  55486. /**
  55487. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55488. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55489. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  55490. * @param nb (positive integer) the number of particles to be created from this model
  55491. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  55492. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  55493. * @returns the number of shapes in the system
  55494. */
  55495. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55496. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55497. var meshInd = mesh.getIndices();
  55498. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55499. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55500. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55501. var bbInfo;
  55502. if (this._particlesIntersect) {
  55503. bbInfo = mesh.getBoundingInfo();
  55504. }
  55505. var shape = this._posToShape(meshPos);
  55506. var shapeUV = this._uvsToShapeUV(meshUV);
  55507. var posfunc = options ? options.positionFunction : null;
  55508. var vtxfunc = options ? options.vertexFunction : null;
  55509. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  55510. // particles
  55511. var sp;
  55512. var currentCopy;
  55513. var idx = this.nbParticles;
  55514. for (var i = 0; i < nb; i++) {
  55515. var currentPos = this._positions.length;
  55516. var currentInd = this._indices.length;
  55517. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  55518. if (this._updatable) {
  55519. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  55520. sp.position.copyFrom(currentCopy.position);
  55521. sp.rotation.copyFrom(currentCopy.rotation);
  55522. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  55523. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  55524. }
  55525. if (currentCopy.color && sp.color) {
  55526. sp.color.copyFrom(currentCopy.color);
  55527. }
  55528. sp.scaling.copyFrom(currentCopy.scaling);
  55529. sp.uvs.copyFrom(currentCopy.uvs);
  55530. }
  55531. this._index += shape.length;
  55532. idx++;
  55533. }
  55534. this.nbParticles += nb;
  55535. this._shapeCounter++;
  55536. return this._shapeCounter - 1;
  55537. };
  55538. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  55539. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  55540. this._resetCopy();
  55541. if (particle._model._positionFunction) {
  55542. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  55543. }
  55544. if (this._copy.rotationQuaternion) {
  55545. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55546. }
  55547. else {
  55548. this._yaw = this._copy.rotation.y;
  55549. this._pitch = this._copy.rotation.x;
  55550. this._roll = this._copy.rotation.z;
  55551. this._quaternionRotationYPR();
  55552. }
  55553. this._quaternionToRotationMatrix();
  55554. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  55555. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  55556. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  55557. if (this._copy.translateFromPivot) {
  55558. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  55559. }
  55560. else {
  55561. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  55562. }
  55563. this._shape = particle._model._shape;
  55564. for (var pt = 0; pt < this._shape.length; pt++) {
  55565. this._vertex.x = this._shape[pt].x;
  55566. this._vertex.y = this._shape[pt].y;
  55567. this._vertex.z = this._shape[pt].z;
  55568. if (particle._model._vertexFunction) {
  55569. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  55570. }
  55571. this._vertex.x *= this._copy.scaling.x;
  55572. this._vertex.y *= this._copy.scaling.y;
  55573. this._vertex.z *= this._copy.scaling.z;
  55574. this._vertex.x -= this._scaledPivot.x;
  55575. this._vertex.y -= this._scaledPivot.y;
  55576. this._vertex.z -= this._scaledPivot.z;
  55577. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55578. this._rotated.addInPlace(this._pivotBackTranslation);
  55579. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  55580. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  55581. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  55582. }
  55583. particle.position.x = 0.0;
  55584. particle.position.y = 0.0;
  55585. particle.position.z = 0.0;
  55586. particle.rotation.x = 0.0;
  55587. particle.rotation.y = 0.0;
  55588. particle.rotation.z = 0.0;
  55589. particle.rotationQuaternion = null;
  55590. particle.scaling.x = 1.0;
  55591. particle.scaling.y = 1.0;
  55592. particle.scaling.z = 1.0;
  55593. particle.uvs.x = 0.0;
  55594. particle.uvs.y = 0.0;
  55595. particle.uvs.z = 1.0;
  55596. particle.uvs.w = 1.0;
  55597. particle.pivot.x = 0.0;
  55598. particle.pivot.y = 0.0;
  55599. particle.pivot.z = 0.0;
  55600. particle.translateFromPivot = false;
  55601. particle.parentId = null;
  55602. };
  55603. /**
  55604. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  55605. * @returns the SPS.
  55606. */
  55607. SolidParticleSystem.prototype.rebuildMesh = function () {
  55608. for (var p = 0; p < this.particles.length; p++) {
  55609. this._rebuildParticle(this.particles[p]);
  55610. }
  55611. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55612. return this;
  55613. };
  55614. /**
  55615. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  55616. * This method calls `updateParticle()` for each particle of the SPS.
  55617. * For an animated SPS, it is usually called within the render loop.
  55618. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  55619. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  55620. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  55621. * @returns the SPS.
  55622. */
  55623. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  55624. if (start === void 0) { start = 0; }
  55625. if (end === void 0) { end = this.nbParticles - 1; }
  55626. if (update === void 0) { update = true; }
  55627. if (!this._updatable) {
  55628. return this;
  55629. }
  55630. // custom beforeUpdate
  55631. this.beforeUpdateParticles(start, end, update);
  55632. this._cam_axisX.x = 1.0;
  55633. this._cam_axisX.y = 0.0;
  55634. this._cam_axisX.z = 0.0;
  55635. this._cam_axisY.x = 0.0;
  55636. this._cam_axisY.y = 1.0;
  55637. this._cam_axisY.z = 0.0;
  55638. this._cam_axisZ.x = 0.0;
  55639. this._cam_axisZ.y = 0.0;
  55640. this._cam_axisZ.z = 1.0;
  55641. // cases when the World Matrix is to be computed first
  55642. if (this.billboard || this._depthSort) {
  55643. this.mesh.computeWorldMatrix(true);
  55644. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  55645. }
  55646. // if the particles will always face the camera
  55647. if (this.billboard) {
  55648. // compute the camera position and un-rotate it by the current mesh rotation
  55649. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  55650. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  55651. this._cam_axisZ.normalize();
  55652. // same for camera up vector extracted from the cam view matrix
  55653. var view = this._camera.getViewMatrix(true);
  55654. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  55655. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  55656. this._cam_axisY.normalize();
  55657. this._cam_axisX.normalize();
  55658. }
  55659. // if depthSort, compute the camera global position in the mesh local system
  55660. if (this._depthSort) {
  55661. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  55662. }
  55663. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  55664. var idx = 0; // current position index in the global array positions32
  55665. var index = 0; // position start index in the global array positions32 of the current particle
  55666. var colidx = 0; // current color index in the global array colors32
  55667. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  55668. var uvidx = 0; // current uv index in the global array uvs32
  55669. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  55670. var pt = 0; // current index in the particle model shape
  55671. if (this.mesh.isFacetDataEnabled) {
  55672. this._computeBoundingBox = true;
  55673. }
  55674. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  55675. if (this._computeBoundingBox) {
  55676. if (start == 0 && end == this.nbParticles - 1) {
  55677. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  55678. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  55679. }
  55680. else {
  55681. if (this.mesh._boundingInfo) {
  55682. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  55683. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  55684. }
  55685. }
  55686. }
  55687. // particle loop
  55688. index = this.particles[start]._pos;
  55689. var vpos = (index / 3) | 0;
  55690. colorIndex = vpos * 4;
  55691. uvIndex = vpos * 2;
  55692. for (var p = start; p <= end; p++) {
  55693. this._particle = this.particles[p];
  55694. this._shape = this._particle._model._shape;
  55695. this._shapeUV = this._particle._model._shapeUV;
  55696. // call to custom user function to update the particle properties
  55697. this.updateParticle(this._particle);
  55698. // camera-particle distance for depth sorting
  55699. if (this._depthSort && this._depthSortParticles) {
  55700. var dsp = this.depthSortedParticles[p];
  55701. dsp.ind = this._particle._ind;
  55702. dsp.indicesLength = this._particle._model._indicesLength;
  55703. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  55704. }
  55705. // skip the computations for inactive or already invisible particles
  55706. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  55707. // increment indexes for the next particle
  55708. pt = this._shape.length;
  55709. index += pt * 3;
  55710. colorIndex += pt * 4;
  55711. uvIndex += pt * 2;
  55712. continue;
  55713. }
  55714. if (this._particle.isVisible) {
  55715. this._particle._stillInvisible = false; // un-mark permanent invisibility
  55716. this._particleHasParent = (this._particle.parentId !== null);
  55717. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  55718. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  55719. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  55720. // particle rotation matrix
  55721. if (this.billboard) {
  55722. this._particle.rotation.x = 0.0;
  55723. this._particle.rotation.y = 0.0;
  55724. }
  55725. if (this._computeParticleRotation || this.billboard) {
  55726. if (this._particle.rotationQuaternion) {
  55727. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55728. }
  55729. else {
  55730. this._yaw = this._particle.rotation.y;
  55731. this._pitch = this._particle.rotation.x;
  55732. this._roll = this._particle.rotation.z;
  55733. this._quaternionRotationYPR();
  55734. }
  55735. this._quaternionToRotationMatrix();
  55736. }
  55737. if (this._particleHasParent) {
  55738. this._parent = this.particles[this._particle.parentId];
  55739. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  55740. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  55741. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  55742. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  55743. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  55744. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  55745. if (this._computeParticleRotation || this.billboard) {
  55746. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  55747. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  55748. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  55749. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  55750. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  55751. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  55752. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  55753. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  55754. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  55755. }
  55756. }
  55757. else {
  55758. this._particle._globalPosition.x = this._particle.position.x;
  55759. this._particle._globalPosition.y = this._particle.position.y;
  55760. this._particle._globalPosition.z = this._particle.position.z;
  55761. if (this._computeParticleRotation || this.billboard) {
  55762. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  55763. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  55764. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  55765. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  55766. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  55767. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  55768. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  55769. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  55770. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  55771. }
  55772. }
  55773. if (this._particle.translateFromPivot) {
  55774. this._pivotBackTranslation.x = 0.0;
  55775. this._pivotBackTranslation.y = 0.0;
  55776. this._pivotBackTranslation.z = 0.0;
  55777. }
  55778. else {
  55779. this._pivotBackTranslation.x = this._scaledPivot.x;
  55780. this._pivotBackTranslation.y = this._scaledPivot.y;
  55781. this._pivotBackTranslation.z = this._scaledPivot.z;
  55782. }
  55783. // particle vertex loop
  55784. for (pt = 0; pt < this._shape.length; pt++) {
  55785. idx = index + pt * 3;
  55786. colidx = colorIndex + pt * 4;
  55787. uvidx = uvIndex + pt * 2;
  55788. this._vertex.x = this._shape[pt].x;
  55789. this._vertex.y = this._shape[pt].y;
  55790. this._vertex.z = this._shape[pt].z;
  55791. if (this._computeParticleVertex) {
  55792. this.updateParticleVertex(this._particle, this._vertex, pt);
  55793. }
  55794. // positions
  55795. this._vertex.x *= this._particle.scaling.x;
  55796. this._vertex.y *= this._particle.scaling.y;
  55797. this._vertex.z *= this._particle.scaling.z;
  55798. this._vertex.x -= this._scaledPivot.x;
  55799. this._vertex.y -= this._scaledPivot.y;
  55800. this._vertex.z -= this._scaledPivot.z;
  55801. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  55802. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  55803. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  55804. this._rotated.x += this._pivotBackTranslation.x;
  55805. this._rotated.y += this._pivotBackTranslation.y;
  55806. this._rotated.z += this._pivotBackTranslation.z;
  55807. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55808. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  55809. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  55810. if (this._computeBoundingBox) {
  55811. if (this._positions32[idx] < this._minimum.x) {
  55812. this._minimum.x = this._positions32[idx];
  55813. }
  55814. if (this._positions32[idx] > this._maximum.x) {
  55815. this._maximum.x = this._positions32[idx];
  55816. }
  55817. if (this._positions32[idx + 1] < this._minimum.y) {
  55818. this._minimum.y = this._positions32[idx + 1];
  55819. }
  55820. if (this._positions32[idx + 1] > this._maximum.y) {
  55821. this._maximum.y = this._positions32[idx + 1];
  55822. }
  55823. if (this._positions32[idx + 2] < this._minimum.z) {
  55824. this._minimum.z = this._positions32[idx + 2];
  55825. }
  55826. if (this._positions32[idx + 2] > this._maximum.z) {
  55827. this._maximum.z = this._positions32[idx + 2];
  55828. }
  55829. }
  55830. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  55831. if (!this._computeParticleVertex) {
  55832. this._normal.x = this._fixedNormal32[idx];
  55833. this._normal.y = this._fixedNormal32[idx + 1];
  55834. this._normal.z = this._fixedNormal32[idx + 2];
  55835. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  55836. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  55837. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  55838. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55839. 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;
  55840. 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;
  55841. }
  55842. if (this._computeParticleColor && this._particle.color) {
  55843. this._colors32[colidx] = this._particle.color.r;
  55844. this._colors32[colidx + 1] = this._particle.color.g;
  55845. this._colors32[colidx + 2] = this._particle.color.b;
  55846. this._colors32[colidx + 3] = this._particle.color.a;
  55847. }
  55848. if (this._computeParticleTexture) {
  55849. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55850. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55851. }
  55852. }
  55853. }
  55854. else {
  55855. this._particle._stillInvisible = true; // mark the particle as invisible
  55856. for (pt = 0; pt < this._shape.length; pt++) {
  55857. idx = index + pt * 3;
  55858. colidx = colorIndex + pt * 4;
  55859. uvidx = uvIndex + pt * 2;
  55860. this._positions32[idx] = 0.0;
  55861. this._positions32[idx + 1] = 0.0;
  55862. this._positions32[idx + 2] = 0.0;
  55863. this._normals32[idx] = 0.0;
  55864. this._normals32[idx + 1] = 0.0;
  55865. this._normals32[idx + 2] = 0.0;
  55866. if (this._computeParticleColor && this._particle.color) {
  55867. this._colors32[colidx] = this._particle.color.r;
  55868. this._colors32[colidx + 1] = this._particle.color.g;
  55869. this._colors32[colidx + 2] = this._particle.color.b;
  55870. this._colors32[colidx + 3] = this._particle.color.a;
  55871. }
  55872. if (this._computeParticleTexture) {
  55873. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55874. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55875. }
  55876. }
  55877. }
  55878. // if the particle intersections must be computed : update the bbInfo
  55879. if (this._particlesIntersect) {
  55880. var bInfo = this._particle._boundingInfo;
  55881. var bBox = bInfo.boundingBox;
  55882. var bSphere = bInfo.boundingSphere;
  55883. if (!this._bSphereOnly) {
  55884. // place, scale and rotate the particle bbox within the SPS local system, then update it
  55885. for (var b = 0; b < bBox.vectors.length; b++) {
  55886. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  55887. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  55888. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  55889. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  55890. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  55891. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  55892. 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;
  55893. 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;
  55894. 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;
  55895. }
  55896. bBox._update(this.mesh._worldMatrix);
  55897. }
  55898. // place and scale the particle bouding sphere in the SPS local system, then update it
  55899. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  55900. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  55901. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  55902. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  55903. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  55904. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  55905. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  55906. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  55907. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  55908. 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));
  55909. bSphere._update(this.mesh._worldMatrix);
  55910. }
  55911. // increment indexes for the next particle
  55912. index = idx + 3;
  55913. colorIndex = colidx + 4;
  55914. uvIndex = uvidx + 2;
  55915. }
  55916. // if the VBO must be updated
  55917. if (update) {
  55918. if (this._computeParticleColor) {
  55919. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55920. }
  55921. if (this._computeParticleTexture) {
  55922. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55923. }
  55924. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55925. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  55926. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  55927. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55928. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  55929. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  55930. for (var i = 0; i < this._normals32.length; i++) {
  55931. this._fixedNormal32[i] = this._normals32[i];
  55932. }
  55933. }
  55934. if (!this.mesh.areNormalsFrozen) {
  55935. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55936. }
  55937. }
  55938. if (this._depthSort && this._depthSortParticles) {
  55939. this.depthSortedParticles.sort(this._depthSortFunction);
  55940. var dspl = this.depthSortedParticles.length;
  55941. var sorted = 0;
  55942. var lind = 0;
  55943. var sind = 0;
  55944. var sid = 0;
  55945. for (sorted = 0; sorted < dspl; sorted++) {
  55946. lind = this.depthSortedParticles[sorted].indicesLength;
  55947. sind = this.depthSortedParticles[sorted].ind;
  55948. for (var i = 0; i < lind; i++) {
  55949. this._indices32[sid] = this._indices[sind + i];
  55950. sid++;
  55951. }
  55952. }
  55953. this.mesh.updateIndices(this._indices32);
  55954. }
  55955. }
  55956. if (this._computeBoundingBox) {
  55957. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55958. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55959. }
  55960. this.afterUpdateParticles(start, end, update);
  55961. return this;
  55962. };
  55963. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55964. this._halfroll = this._roll * 0.5;
  55965. this._halfpitch = this._pitch * 0.5;
  55966. this._halfyaw = this._yaw * 0.5;
  55967. this._sinRoll = Math.sin(this._halfroll);
  55968. this._cosRoll = Math.cos(this._halfroll);
  55969. this._sinPitch = Math.sin(this._halfpitch);
  55970. this._cosPitch = Math.cos(this._halfpitch);
  55971. this._sinYaw = Math.sin(this._halfyaw);
  55972. this._cosYaw = Math.cos(this._halfyaw);
  55973. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  55974. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  55975. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  55976. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  55977. };
  55978. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55979. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55980. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55981. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55982. this._rotMatrix.m[3] = 0;
  55983. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55984. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55985. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55986. this._rotMatrix.m[7] = 0;
  55987. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55988. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55989. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55990. this._rotMatrix.m[11] = 0;
  55991. this._rotMatrix.m[12] = 0;
  55992. this._rotMatrix.m[13] = 0;
  55993. this._rotMatrix.m[14] = 0;
  55994. this._rotMatrix.m[15] = 1.0;
  55995. };
  55996. /**
  55997. * Disposes the SPS.
  55998. */
  55999. SolidParticleSystem.prototype.dispose = function () {
  56000. this.mesh.dispose();
  56001. this.vars = null;
  56002. // drop references to internal big arrays for the GC
  56003. this._positions = null;
  56004. this._indices = null;
  56005. this._normals = null;
  56006. this._uvs = null;
  56007. this._colors = null;
  56008. this._indices32 = null;
  56009. this._positions32 = null;
  56010. this._normals32 = null;
  56011. this._fixedNormal32 = null;
  56012. this._uvs32 = null;
  56013. this._colors32 = null;
  56014. this.pickedParticles = null;
  56015. };
  56016. /**
  56017. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  56018. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56019. * @returns the SPS.
  56020. */
  56021. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  56022. if (!this._isVisibilityBoxLocked) {
  56023. this.mesh.refreshBoundingInfo();
  56024. }
  56025. return this;
  56026. };
  56027. /**
  56028. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  56029. * @param size the size (float) of the visibility box
  56030. * note : this doesn't lock the SPS mesh bounding box.
  56031. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56032. */
  56033. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  56034. var vis = size / 2;
  56035. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  56036. };
  56037. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  56038. /**
  56039. * Gets whether the SPS as always visible or not
  56040. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56041. */
  56042. get: function () {
  56043. return this._alwaysVisible;
  56044. },
  56045. /**
  56046. * Sets the SPS as always visible or not
  56047. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56048. */
  56049. set: function (val) {
  56050. this._alwaysVisible = val;
  56051. this.mesh.alwaysSelectAsActiveMesh = val;
  56052. },
  56053. enumerable: true,
  56054. configurable: true
  56055. });
  56056. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  56057. /**
  56058. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  56059. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56060. */
  56061. get: function () {
  56062. return this._isVisibilityBoxLocked;
  56063. },
  56064. /**
  56065. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  56066. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56067. */
  56068. set: function (val) {
  56069. this._isVisibilityBoxLocked = val;
  56070. var boundingInfo = this.mesh.getBoundingInfo();
  56071. boundingInfo.isLocked = val;
  56072. },
  56073. enumerable: true,
  56074. configurable: true
  56075. });
  56076. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  56077. /**
  56078. * Gets if `setParticles()` computes the particle rotations or not.
  56079. * Default value : true. The SPS is faster when it's set to false.
  56080. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  56081. */
  56082. get: function () {
  56083. return this._computeParticleRotation;
  56084. },
  56085. /**
  56086. * Tells to `setParticles()` to compute the particle rotations or not.
  56087. * Default value : true. The SPS is faster when it's set to false.
  56088. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  56089. */
  56090. set: function (val) {
  56091. this._computeParticleRotation = val;
  56092. },
  56093. enumerable: true,
  56094. configurable: true
  56095. });
  56096. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  56097. /**
  56098. * Gets if `setParticles()` computes the particle colors or not.
  56099. * Default value : true. The SPS is faster when it's set to false.
  56100. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  56101. */
  56102. get: function () {
  56103. return this._computeParticleColor;
  56104. },
  56105. /**
  56106. * Tells to `setParticles()` to compute the particle colors or not.
  56107. * Default value : true. The SPS is faster when it's set to false.
  56108. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  56109. */
  56110. set: function (val) {
  56111. this._computeParticleColor = val;
  56112. },
  56113. enumerable: true,
  56114. configurable: true
  56115. });
  56116. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  56117. /**
  56118. * Gets if `setParticles()` computes the particle textures or not.
  56119. * Default value : true. The SPS is faster when it's set to false.
  56120. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  56121. */
  56122. get: function () {
  56123. return this._computeParticleTexture;
  56124. },
  56125. set: function (val) {
  56126. this._computeParticleTexture = val;
  56127. },
  56128. enumerable: true,
  56129. configurable: true
  56130. });
  56131. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  56132. /**
  56133. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  56134. * Default value : false. The SPS is faster when it's set to false.
  56135. * Note : the particle custom vertex positions aren't stored values.
  56136. */
  56137. get: function () {
  56138. return this._computeParticleVertex;
  56139. },
  56140. /**
  56141. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  56142. * Default value : false. The SPS is faster when it's set to false.
  56143. * Note : the particle custom vertex positions aren't stored values.
  56144. */
  56145. set: function (val) {
  56146. this._computeParticleVertex = val;
  56147. },
  56148. enumerable: true,
  56149. configurable: true
  56150. });
  56151. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  56152. /**
  56153. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  56154. */
  56155. get: function () {
  56156. return this._computeBoundingBox;
  56157. },
  56158. /**
  56159. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  56160. */
  56161. set: function (val) {
  56162. this._computeBoundingBox = val;
  56163. },
  56164. enumerable: true,
  56165. configurable: true
  56166. });
  56167. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  56168. /**
  56169. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  56170. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  56171. * Default : `true`
  56172. */
  56173. get: function () {
  56174. return this._depthSortParticles;
  56175. },
  56176. /**
  56177. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  56178. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  56179. * Default : `true`
  56180. */
  56181. set: function (val) {
  56182. this._depthSortParticles = val;
  56183. },
  56184. enumerable: true,
  56185. configurable: true
  56186. });
  56187. // =======================================================================
  56188. // Particle behavior logic
  56189. // these following methods may be overwritten by the user to fit his needs
  56190. /**
  56191. * This function does nothing. It may be overwritten to set all the particle first values.
  56192. * The SPS doesn't call this function, you may have to call it by your own.
  56193. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56194. */
  56195. SolidParticleSystem.prototype.initParticles = function () {
  56196. };
  56197. /**
  56198. * This function does nothing. It may be overwritten to recycle a particle.
  56199. * The SPS doesn't call this function, you may have to call it by your own.
  56200. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56201. * @param particle The particle to recycle
  56202. * @returns the recycled particle
  56203. */
  56204. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  56205. return particle;
  56206. };
  56207. /**
  56208. * Updates a particle : this function should be overwritten by the user.
  56209. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  56210. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56211. * @example : just set a particle position or velocity and recycle conditions
  56212. * @param particle The particle to update
  56213. * @returns the updated particle
  56214. */
  56215. SolidParticleSystem.prototype.updateParticle = function (particle) {
  56216. return particle;
  56217. };
  56218. /**
  56219. * Updates a vertex of a particle : it can be overwritten by the user.
  56220. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  56221. * @param particle the current particle
  56222. * @param vertex the current index of the current particle
  56223. * @param pt the index of the current vertex in the particle shape
  56224. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  56225. * @example : just set a vertex particle position
  56226. * @returns the updated vertex
  56227. */
  56228. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  56229. return vertex;
  56230. };
  56231. /**
  56232. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  56233. * This does nothing and may be overwritten by the user.
  56234. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56235. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56236. * @param update the boolean update value actually passed to setParticles()
  56237. */
  56238. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  56239. };
  56240. /**
  56241. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  56242. * This will be passed three parameters.
  56243. * This does nothing and may be overwritten by the user.
  56244. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56245. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56246. * @param update the boolean update value actually passed to setParticles()
  56247. */
  56248. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  56249. };
  56250. return SolidParticleSystem;
  56251. }());
  56252. BABYLON.SolidParticleSystem = SolidParticleSystem;
  56253. })(BABYLON || (BABYLON = {}));
  56254. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  56255. "use strict";
  56256. var BABYLON;
  56257. (function (BABYLON) {
  56258. var ShaderMaterial = /** @class */ (function (_super) {
  56259. __extends(ShaderMaterial, _super);
  56260. function ShaderMaterial(name, scene, shaderPath, options) {
  56261. var _this = _super.call(this, name, scene) || this;
  56262. _this._textures = {};
  56263. _this._textureArrays = {};
  56264. _this._floats = {};
  56265. _this._ints = {};
  56266. _this._floatsArrays = {};
  56267. _this._colors3 = {};
  56268. _this._colors3Arrays = {};
  56269. _this._colors4 = {};
  56270. _this._vectors2 = {};
  56271. _this._vectors3 = {};
  56272. _this._vectors4 = {};
  56273. _this._matrices = {};
  56274. _this._matrices3x3 = {};
  56275. _this._matrices2x2 = {};
  56276. _this._vectors2Arrays = {};
  56277. _this._vectors3Arrays = {};
  56278. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  56279. _this._shaderPath = shaderPath;
  56280. options.needAlphaBlending = options.needAlphaBlending || false;
  56281. options.needAlphaTesting = options.needAlphaTesting || false;
  56282. options.attributes = options.attributes || ["position", "normal", "uv"];
  56283. options.uniforms = options.uniforms || ["worldViewProjection"];
  56284. options.uniformBuffers = options.uniformBuffers || [];
  56285. options.samplers = options.samplers || [];
  56286. options.defines = options.defines || [];
  56287. _this._options = options;
  56288. return _this;
  56289. }
  56290. ShaderMaterial.prototype.getClassName = function () {
  56291. return "ShaderMaterial";
  56292. };
  56293. ShaderMaterial.prototype.needAlphaBlending = function () {
  56294. return this._options.needAlphaBlending;
  56295. };
  56296. ShaderMaterial.prototype.needAlphaTesting = function () {
  56297. return this._options.needAlphaTesting;
  56298. };
  56299. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  56300. if (this._options.uniforms.indexOf(uniformName) === -1) {
  56301. this._options.uniforms.push(uniformName);
  56302. }
  56303. };
  56304. ShaderMaterial.prototype.setTexture = function (name, texture) {
  56305. if (this._options.samplers.indexOf(name) === -1) {
  56306. this._options.samplers.push(name);
  56307. }
  56308. this._textures[name] = texture;
  56309. return this;
  56310. };
  56311. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  56312. if (this._options.samplers.indexOf(name) === -1) {
  56313. this._options.samplers.push(name);
  56314. }
  56315. this._checkUniform(name);
  56316. this._textureArrays[name] = textures;
  56317. return this;
  56318. };
  56319. ShaderMaterial.prototype.setFloat = function (name, value) {
  56320. this._checkUniform(name);
  56321. this._floats[name] = value;
  56322. return this;
  56323. };
  56324. ShaderMaterial.prototype.setInt = function (name, value) {
  56325. this._checkUniform(name);
  56326. this._ints[name] = value;
  56327. return this;
  56328. };
  56329. ShaderMaterial.prototype.setFloats = function (name, value) {
  56330. this._checkUniform(name);
  56331. this._floatsArrays[name] = value;
  56332. return this;
  56333. };
  56334. ShaderMaterial.prototype.setColor3 = function (name, value) {
  56335. this._checkUniform(name);
  56336. this._colors3[name] = value;
  56337. return this;
  56338. };
  56339. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  56340. this._checkUniform(name);
  56341. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  56342. color.toArray(arr, arr.length);
  56343. return arr;
  56344. }, []);
  56345. return this;
  56346. };
  56347. ShaderMaterial.prototype.setColor4 = function (name, value) {
  56348. this._checkUniform(name);
  56349. this._colors4[name] = value;
  56350. return this;
  56351. };
  56352. ShaderMaterial.prototype.setVector2 = function (name, value) {
  56353. this._checkUniform(name);
  56354. this._vectors2[name] = value;
  56355. return this;
  56356. };
  56357. ShaderMaterial.prototype.setVector3 = function (name, value) {
  56358. this._checkUniform(name);
  56359. this._vectors3[name] = value;
  56360. return this;
  56361. };
  56362. ShaderMaterial.prototype.setVector4 = function (name, value) {
  56363. this._checkUniform(name);
  56364. this._vectors4[name] = value;
  56365. return this;
  56366. };
  56367. ShaderMaterial.prototype.setMatrix = function (name, value) {
  56368. this._checkUniform(name);
  56369. this._matrices[name] = value;
  56370. return this;
  56371. };
  56372. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  56373. this._checkUniform(name);
  56374. this._matrices3x3[name] = value;
  56375. return this;
  56376. };
  56377. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  56378. this._checkUniform(name);
  56379. this._matrices2x2[name] = value;
  56380. return this;
  56381. };
  56382. ShaderMaterial.prototype.setArray2 = function (name, value) {
  56383. this._checkUniform(name);
  56384. this._vectors2Arrays[name] = value;
  56385. return this;
  56386. };
  56387. ShaderMaterial.prototype.setArray3 = function (name, value) {
  56388. this._checkUniform(name);
  56389. this._vectors3Arrays[name] = value;
  56390. return this;
  56391. };
  56392. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  56393. if (!mesh) {
  56394. return true;
  56395. }
  56396. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  56397. return false;
  56398. }
  56399. return false;
  56400. };
  56401. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  56402. var scene = this.getScene();
  56403. var engine = scene.getEngine();
  56404. if (!this.checkReadyOnEveryCall) {
  56405. if (this._renderId === scene.getRenderId()) {
  56406. if (this._checkCache(scene, mesh, useInstances)) {
  56407. return true;
  56408. }
  56409. }
  56410. }
  56411. // Instances
  56412. var defines = [];
  56413. var attribs = [];
  56414. var fallbacks = new BABYLON.EffectFallbacks();
  56415. if (useInstances) {
  56416. defines.push("#define INSTANCES");
  56417. }
  56418. for (var index = 0; index < this._options.defines.length; index++) {
  56419. defines.push(this._options.defines[index]);
  56420. }
  56421. for (var index = 0; index < this._options.attributes.length; index++) {
  56422. attribs.push(this._options.attributes[index]);
  56423. }
  56424. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  56425. attribs.push(BABYLON.VertexBuffer.ColorKind);
  56426. defines.push("#define VERTEXCOLOR");
  56427. }
  56428. // Bones
  56429. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56430. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56431. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56432. if (mesh.numBoneInfluencers > 4) {
  56433. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56434. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56435. }
  56436. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56437. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56438. fallbacks.addCPUSkinningFallback(0, mesh);
  56439. if (this._options.uniforms.indexOf("mBones") === -1) {
  56440. this._options.uniforms.push("mBones");
  56441. }
  56442. }
  56443. else {
  56444. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56445. }
  56446. // Textures
  56447. for (var name in this._textures) {
  56448. if (!this._textures[name].isReady()) {
  56449. return false;
  56450. }
  56451. }
  56452. // Alpha test
  56453. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  56454. defines.push("#define ALPHATEST");
  56455. }
  56456. var previousEffect = this._effect;
  56457. var join = defines.join("\n");
  56458. this._effect = engine.createEffect(this._shaderPath, {
  56459. attributes: attribs,
  56460. uniformsNames: this._options.uniforms,
  56461. uniformBuffersNames: this._options.uniformBuffers,
  56462. samplers: this._options.samplers,
  56463. defines: join,
  56464. fallbacks: fallbacks,
  56465. onCompiled: this.onCompiled,
  56466. onError: this.onError
  56467. }, engine);
  56468. if (!this._effect.isReady()) {
  56469. return false;
  56470. }
  56471. if (previousEffect !== this._effect) {
  56472. scene.resetCachedMaterial();
  56473. }
  56474. this._renderId = scene.getRenderId();
  56475. return true;
  56476. };
  56477. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  56478. var scene = this.getScene();
  56479. if (!this._effect) {
  56480. return;
  56481. }
  56482. if (this._options.uniforms.indexOf("world") !== -1) {
  56483. this._effect.setMatrix("world", world);
  56484. }
  56485. if (this._options.uniforms.indexOf("worldView") !== -1) {
  56486. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  56487. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  56488. }
  56489. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  56490. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  56491. }
  56492. };
  56493. ShaderMaterial.prototype.bind = function (world, mesh) {
  56494. // Std values
  56495. this.bindOnlyWorldMatrix(world);
  56496. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  56497. if (this._options.uniforms.indexOf("view") !== -1) {
  56498. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  56499. }
  56500. if (this._options.uniforms.indexOf("projection") !== -1) {
  56501. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  56502. }
  56503. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  56504. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  56505. }
  56506. // Bones
  56507. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  56508. var name;
  56509. // Texture
  56510. for (name in this._textures) {
  56511. this._effect.setTexture(name, this._textures[name]);
  56512. }
  56513. // Texture arrays
  56514. for (name in this._textureArrays) {
  56515. this._effect.setTextureArray(name, this._textureArrays[name]);
  56516. }
  56517. // Int
  56518. for (name in this._ints) {
  56519. this._effect.setInt(name, this._ints[name]);
  56520. }
  56521. // Float
  56522. for (name in this._floats) {
  56523. this._effect.setFloat(name, this._floats[name]);
  56524. }
  56525. // Floats
  56526. for (name in this._floatsArrays) {
  56527. this._effect.setArray(name, this._floatsArrays[name]);
  56528. }
  56529. // Color3
  56530. for (name in this._colors3) {
  56531. this._effect.setColor3(name, this._colors3[name]);
  56532. }
  56533. for (name in this._colors3Arrays) {
  56534. this._effect.setArray3(name, this._colors3Arrays[name]);
  56535. }
  56536. // Color4
  56537. for (name in this._colors4) {
  56538. var color = this._colors4[name];
  56539. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  56540. }
  56541. // Vector2
  56542. for (name in this._vectors2) {
  56543. this._effect.setVector2(name, this._vectors2[name]);
  56544. }
  56545. // Vector3
  56546. for (name in this._vectors3) {
  56547. this._effect.setVector3(name, this._vectors3[name]);
  56548. }
  56549. // Vector4
  56550. for (name in this._vectors4) {
  56551. this._effect.setVector4(name, this._vectors4[name]);
  56552. }
  56553. // Matrix
  56554. for (name in this._matrices) {
  56555. this._effect.setMatrix(name, this._matrices[name]);
  56556. }
  56557. // Matrix 3x3
  56558. for (name in this._matrices3x3) {
  56559. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  56560. }
  56561. // Matrix 2x2
  56562. for (name in this._matrices2x2) {
  56563. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  56564. }
  56565. // Vector2Array
  56566. for (name in this._vectors2Arrays) {
  56567. this._effect.setArray2(name, this._vectors2Arrays[name]);
  56568. }
  56569. // Vector3Array
  56570. for (name in this._vectors3Arrays) {
  56571. this._effect.setArray3(name, this._vectors3Arrays[name]);
  56572. }
  56573. }
  56574. this._afterBind(mesh);
  56575. };
  56576. ShaderMaterial.prototype.getActiveTextures = function () {
  56577. var activeTextures = _super.prototype.getActiveTextures.call(this);
  56578. for (var name in this._textures) {
  56579. activeTextures.push(this._textures[name]);
  56580. }
  56581. for (var name in this._textureArrays) {
  56582. var array = this._textureArrays[name];
  56583. for (var index = 0; index < array.length; index++) {
  56584. activeTextures.push(array[index]);
  56585. }
  56586. }
  56587. return activeTextures;
  56588. };
  56589. ShaderMaterial.prototype.hasTexture = function (texture) {
  56590. if (_super.prototype.hasTexture.call(this, texture)) {
  56591. return true;
  56592. }
  56593. for (var name in this._textures) {
  56594. if (this._textures[name] === texture) {
  56595. return true;
  56596. }
  56597. }
  56598. for (var name in this._textureArrays) {
  56599. var array = this._textureArrays[name];
  56600. for (var index = 0; index < array.length; index++) {
  56601. if (array[index] === texture) {
  56602. return true;
  56603. }
  56604. }
  56605. }
  56606. return false;
  56607. };
  56608. ShaderMaterial.prototype.clone = function (name) {
  56609. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  56610. return newShaderMaterial;
  56611. };
  56612. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56613. if (forceDisposeTextures) {
  56614. var name;
  56615. for (name in this._textures) {
  56616. this._textures[name].dispose();
  56617. }
  56618. for (name in this._textureArrays) {
  56619. var array = this._textureArrays[name];
  56620. for (var index = 0; index < array.length; index++) {
  56621. array[index].dispose();
  56622. }
  56623. }
  56624. }
  56625. this._textures = {};
  56626. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56627. };
  56628. ShaderMaterial.prototype.serialize = function () {
  56629. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  56630. serializationObject.customType = "BABYLON.ShaderMaterial";
  56631. serializationObject.options = this._options;
  56632. serializationObject.shaderPath = this._shaderPath;
  56633. var name;
  56634. // Texture
  56635. serializationObject.textures = {};
  56636. for (name in this._textures) {
  56637. serializationObject.textures[name] = this._textures[name].serialize();
  56638. }
  56639. // Texture arrays
  56640. serializationObject.textureArrays = {};
  56641. for (name in this._textureArrays) {
  56642. serializationObject.textureArrays[name] = [];
  56643. var array = this._textureArrays[name];
  56644. for (var index = 0; index < array.length; index++) {
  56645. serializationObject.textureArrays[name].push(array[index].serialize());
  56646. }
  56647. }
  56648. // Float
  56649. serializationObject.floats = {};
  56650. for (name in this._floats) {
  56651. serializationObject.floats[name] = this._floats[name];
  56652. }
  56653. // Float s
  56654. serializationObject.FloatArrays = {};
  56655. for (name in this._floatsArrays) {
  56656. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  56657. }
  56658. // Color3
  56659. serializationObject.colors3 = {};
  56660. for (name in this._colors3) {
  56661. serializationObject.colors3[name] = this._colors3[name].asArray();
  56662. }
  56663. // Color3 array
  56664. serializationObject.colors3Arrays = {};
  56665. for (name in this._colors3Arrays) {
  56666. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  56667. }
  56668. // Color4
  56669. serializationObject.colors4 = {};
  56670. for (name in this._colors4) {
  56671. serializationObject.colors4[name] = this._colors4[name].asArray();
  56672. }
  56673. // Vector2
  56674. serializationObject.vectors2 = {};
  56675. for (name in this._vectors2) {
  56676. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  56677. }
  56678. // Vector3
  56679. serializationObject.vectors3 = {};
  56680. for (name in this._vectors3) {
  56681. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  56682. }
  56683. // Vector4
  56684. serializationObject.vectors4 = {};
  56685. for (name in this._vectors4) {
  56686. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  56687. }
  56688. // Matrix
  56689. serializationObject.matrices = {};
  56690. for (name in this._matrices) {
  56691. serializationObject.matrices[name] = this._matrices[name].asArray();
  56692. }
  56693. // Matrix 3x3
  56694. serializationObject.matrices3x3 = {};
  56695. for (name in this._matrices3x3) {
  56696. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  56697. }
  56698. // Matrix 2x2
  56699. serializationObject.matrices2x2 = {};
  56700. for (name in this._matrices2x2) {
  56701. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  56702. }
  56703. // Vector2Array
  56704. serializationObject.vectors2Arrays = {};
  56705. for (name in this._vectors2Arrays) {
  56706. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  56707. }
  56708. // Vector3Array
  56709. serializationObject.vectors3Arrays = {};
  56710. for (name in this._vectors3Arrays) {
  56711. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  56712. }
  56713. return serializationObject;
  56714. };
  56715. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  56716. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  56717. var name;
  56718. // Texture
  56719. for (name in source.textures) {
  56720. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  56721. }
  56722. // Texture arrays
  56723. for (name in source.textureArrays) {
  56724. var array = source.textureArrays[name];
  56725. var textureArray = new Array();
  56726. for (var index = 0; index < array.length; index++) {
  56727. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  56728. }
  56729. material.setTextureArray(name, textureArray);
  56730. }
  56731. // Float
  56732. for (name in source.floats) {
  56733. material.setFloat(name, source.floats[name]);
  56734. }
  56735. // Float s
  56736. for (name in source.floatsArrays) {
  56737. material.setFloats(name, source.floatsArrays[name]);
  56738. }
  56739. // Color3
  56740. for (name in source.colors3) {
  56741. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  56742. }
  56743. // Color3 arrays
  56744. for (name in source.colors3Arrays) {
  56745. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  56746. if (i % 3 === 0) {
  56747. arr.push([num]);
  56748. }
  56749. else {
  56750. arr[arr.length - 1].push(num);
  56751. }
  56752. return arr;
  56753. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  56754. material.setColor3Array(name, colors);
  56755. }
  56756. // Color4
  56757. for (name in source.colors4) {
  56758. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  56759. }
  56760. // Vector2
  56761. for (name in source.vectors2) {
  56762. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  56763. }
  56764. // Vector3
  56765. for (name in source.vectors3) {
  56766. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  56767. }
  56768. // Vector4
  56769. for (name in source.vectors4) {
  56770. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  56771. }
  56772. // Matrix
  56773. for (name in source.matrices) {
  56774. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  56775. }
  56776. // Matrix 3x3
  56777. for (name in source.matrices3x3) {
  56778. material.setMatrix3x3(name, source.matrices3x3[name]);
  56779. }
  56780. // Matrix 2x2
  56781. for (name in source.matrices2x2) {
  56782. material.setMatrix2x2(name, source.matrices2x2[name]);
  56783. }
  56784. // Vector2Array
  56785. for (name in source.vectors2Arrays) {
  56786. material.setArray2(name, source.vectors2Arrays[name]);
  56787. }
  56788. // Vector3Array
  56789. for (name in source.vectors3Arrays) {
  56790. material.setArray3(name, source.vectors3Arrays[name]);
  56791. }
  56792. return material;
  56793. };
  56794. return ShaderMaterial;
  56795. }(BABYLON.Material));
  56796. BABYLON.ShaderMaterial = ShaderMaterial;
  56797. })(BABYLON || (BABYLON = {}));
  56798. //# sourceMappingURL=babylon.shaderMaterial.js.map
  56799. "use strict";
  56800. var BABYLON;
  56801. (function (BABYLON) {
  56802. var GroundMesh = /** @class */ (function (_super) {
  56803. __extends(GroundMesh, _super);
  56804. function GroundMesh(name, scene) {
  56805. var _this = _super.call(this, name, scene) || this;
  56806. _this.generateOctree = false;
  56807. return _this;
  56808. }
  56809. GroundMesh.prototype.getClassName = function () {
  56810. return "GroundMesh";
  56811. };
  56812. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  56813. get: function () {
  56814. return Math.min(this._subdivisionsX, this._subdivisionsY);
  56815. },
  56816. enumerable: true,
  56817. configurable: true
  56818. });
  56819. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  56820. get: function () {
  56821. return this._subdivisionsX;
  56822. },
  56823. enumerable: true,
  56824. configurable: true
  56825. });
  56826. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  56827. get: function () {
  56828. return this._subdivisionsY;
  56829. },
  56830. enumerable: true,
  56831. configurable: true
  56832. });
  56833. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  56834. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  56835. this._subdivisionsX = chunksCount;
  56836. this._subdivisionsY = chunksCount;
  56837. this.subdivide(chunksCount);
  56838. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  56839. };
  56840. /**
  56841. * Returns a height (y) value in the Worl system :
  56842. * the ground altitude at the coordinates (x, z) expressed in the World system.
  56843. * Returns the ground y position if (x, z) are outside the ground surface.
  56844. */
  56845. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  56846. var world = this.getWorldMatrix();
  56847. var invMat = BABYLON.Tmp.Matrix[5];
  56848. world.invertToRef(invMat);
  56849. var tmpVect = BABYLON.Tmp.Vector3[8];
  56850. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  56851. x = tmpVect.x;
  56852. z = tmpVect.z;
  56853. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  56854. return this.position.y;
  56855. }
  56856. if (!this._heightQuads || this._heightQuads.length == 0) {
  56857. this._initHeightQuads();
  56858. this._computeHeightQuads();
  56859. }
  56860. var facet = this._getFacetAt(x, z);
  56861. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  56862. // return y in the World system
  56863. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  56864. return tmpVect.y;
  56865. };
  56866. /**
  56867. * Returns a normalized vector (Vector3) orthogonal to the ground
  56868. * at the ground coordinates (x, z) expressed in the World system.
  56869. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  56870. */
  56871. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  56872. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  56873. this.getNormalAtCoordinatesToRef(x, z, normal);
  56874. return normal;
  56875. };
  56876. /**
  56877. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  56878. * at the ground coordinates (x, z) expressed in the World system.
  56879. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  56880. * Returns the GroundMesh.
  56881. */
  56882. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  56883. var world = this.getWorldMatrix();
  56884. var tmpMat = BABYLON.Tmp.Matrix[5];
  56885. world.invertToRef(tmpMat);
  56886. var tmpVect = BABYLON.Tmp.Vector3[8];
  56887. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  56888. x = tmpVect.x;
  56889. z = tmpVect.z;
  56890. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  56891. return this;
  56892. }
  56893. if (!this._heightQuads || this._heightQuads.length == 0) {
  56894. this._initHeightQuads();
  56895. this._computeHeightQuads();
  56896. }
  56897. var facet = this._getFacetAt(x, z);
  56898. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  56899. return this;
  56900. };
  56901. /**
  56902. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  56903. * if the ground has been updated.
  56904. * This can be used in the render loop.
  56905. * Returns the GroundMesh.
  56906. */
  56907. GroundMesh.prototype.updateCoordinateHeights = function () {
  56908. if (!this._heightQuads || this._heightQuads.length == 0) {
  56909. this._initHeightQuads();
  56910. }
  56911. this._computeHeightQuads();
  56912. return this;
  56913. };
  56914. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  56915. GroundMesh.prototype._getFacetAt = function (x, z) {
  56916. // retrieve col and row from x, z coordinates in the ground local system
  56917. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  56918. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  56919. var quad = this._heightQuads[row * this._subdivisionsX + col];
  56920. var facet;
  56921. if (z < quad.slope.x * x + quad.slope.y) {
  56922. facet = quad.facet1;
  56923. }
  56924. else {
  56925. facet = quad.facet2;
  56926. }
  56927. return facet;
  56928. };
  56929. // Creates and populates the heightMap array with "facet" elements :
  56930. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  56931. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56932. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56933. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56934. // Returns the GroundMesh.
  56935. GroundMesh.prototype._initHeightQuads = function () {
  56936. var subdivisionsX = this._subdivisionsX;
  56937. var subdivisionsY = this._subdivisionsY;
  56938. this._heightQuads = new Array();
  56939. for (var row = 0; row < subdivisionsY; row++) {
  56940. for (var col = 0; col < subdivisionsX; col++) {
  56941. 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) };
  56942. this._heightQuads[row * subdivisionsX + col] = quad;
  56943. }
  56944. }
  56945. return this;
  56946. };
  56947. // Compute each quad element values and update the the heightMap array :
  56948. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56949. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56950. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56951. // Returns the GroundMesh.
  56952. GroundMesh.prototype._computeHeightQuads = function () {
  56953. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56954. if (!positions) {
  56955. return this;
  56956. }
  56957. var v1 = BABYLON.Tmp.Vector3[3];
  56958. var v2 = BABYLON.Tmp.Vector3[2];
  56959. var v3 = BABYLON.Tmp.Vector3[1];
  56960. var v4 = BABYLON.Tmp.Vector3[0];
  56961. var v1v2 = BABYLON.Tmp.Vector3[4];
  56962. var v1v3 = BABYLON.Tmp.Vector3[5];
  56963. var v1v4 = BABYLON.Tmp.Vector3[6];
  56964. var norm1 = BABYLON.Tmp.Vector3[7];
  56965. var norm2 = BABYLON.Tmp.Vector3[8];
  56966. var i = 0;
  56967. var j = 0;
  56968. var k = 0;
  56969. var cd = 0; // 2D slope coefficient : z = cd * x + h
  56970. var h = 0;
  56971. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  56972. var d2 = 0;
  56973. var subdivisionsX = this._subdivisionsX;
  56974. var subdivisionsY = this._subdivisionsY;
  56975. for (var row = 0; row < subdivisionsY; row++) {
  56976. for (var col = 0; col < subdivisionsX; col++) {
  56977. i = col * 3;
  56978. j = row * (subdivisionsX + 1) * 3;
  56979. k = (row + 1) * (subdivisionsX + 1) * 3;
  56980. v1.x = positions[j + i];
  56981. v1.y = positions[j + i + 1];
  56982. v1.z = positions[j + i + 2];
  56983. v2.x = positions[j + i + 3];
  56984. v2.y = positions[j + i + 4];
  56985. v2.z = positions[j + i + 5];
  56986. v3.x = positions[k + i];
  56987. v3.y = positions[k + i + 1];
  56988. v3.z = positions[k + i + 2];
  56989. v4.x = positions[k + i + 3];
  56990. v4.y = positions[k + i + 4];
  56991. v4.z = positions[k + i + 5];
  56992. // 2D slope V1V4
  56993. cd = (v4.z - v1.z) / (v4.x - v1.x);
  56994. h = v1.z - cd * v1.x; // v1 belongs to the slope
  56995. // facet equations :
  56996. // we compute each facet normal vector
  56997. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  56998. // we compute the value d by applying the equation to v1 which belongs to the plane
  56999. // then we store the facet equation in a Vector4
  57000. v2.subtractToRef(v1, v1v2);
  57001. v3.subtractToRef(v1, v1v3);
  57002. v4.subtractToRef(v1, v1v4);
  57003. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  57004. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  57005. norm1.normalize();
  57006. norm2.normalize();
  57007. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  57008. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  57009. var quad = this._heightQuads[row * subdivisionsX + col];
  57010. quad.slope.copyFromFloats(cd, h);
  57011. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  57012. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  57013. }
  57014. }
  57015. return this;
  57016. };
  57017. GroundMesh.prototype.serialize = function (serializationObject) {
  57018. _super.prototype.serialize.call(this, serializationObject);
  57019. serializationObject.subdivisionsX = this._subdivisionsX;
  57020. serializationObject.subdivisionsY = this._subdivisionsY;
  57021. serializationObject.minX = this._minX;
  57022. serializationObject.maxX = this._maxX;
  57023. serializationObject.minZ = this._minZ;
  57024. serializationObject.maxZ = this._maxZ;
  57025. serializationObject.width = this._width;
  57026. serializationObject.height = this._height;
  57027. };
  57028. GroundMesh.Parse = function (parsedMesh, scene) {
  57029. var result = new GroundMesh(parsedMesh.name, scene);
  57030. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  57031. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  57032. result._minX = parsedMesh.minX;
  57033. result._maxX = parsedMesh.maxX;
  57034. result._minZ = parsedMesh.minZ;
  57035. result._maxZ = parsedMesh.maxZ;
  57036. result._width = parsedMesh.width;
  57037. result._height = parsedMesh.height;
  57038. return result;
  57039. };
  57040. return GroundMesh;
  57041. }(BABYLON.Mesh));
  57042. BABYLON.GroundMesh = GroundMesh;
  57043. })(BABYLON || (BABYLON = {}));
  57044. //# sourceMappingURL=babylon.groundMesh.js.map
  57045. "use strict";
  57046. var BABYLON;
  57047. (function (BABYLON) {
  57048. /**
  57049. * Creates an instance based on a source mesh.
  57050. */
  57051. var InstancedMesh = /** @class */ (function (_super) {
  57052. __extends(InstancedMesh, _super);
  57053. function InstancedMesh(name, source) {
  57054. var _this = _super.call(this, name, source.getScene()) || this;
  57055. source.instances.push(_this);
  57056. _this._sourceMesh = source;
  57057. _this.position.copyFrom(source.position);
  57058. _this.rotation.copyFrom(source.rotation);
  57059. _this.scaling.copyFrom(source.scaling);
  57060. if (source.rotationQuaternion) {
  57061. _this.rotationQuaternion = source.rotationQuaternion.clone();
  57062. }
  57063. _this.infiniteDistance = source.infiniteDistance;
  57064. _this.setPivotMatrix(source.getPivotMatrix());
  57065. _this.refreshBoundingInfo();
  57066. _this._syncSubMeshes();
  57067. return _this;
  57068. }
  57069. /**
  57070. * Returns the string "InstancedMesh".
  57071. */
  57072. InstancedMesh.prototype.getClassName = function () {
  57073. return "InstancedMesh";
  57074. };
  57075. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  57076. // Methods
  57077. get: function () {
  57078. return this._sourceMesh.receiveShadows;
  57079. },
  57080. enumerable: true,
  57081. configurable: true
  57082. });
  57083. Object.defineProperty(InstancedMesh.prototype, "material", {
  57084. get: function () {
  57085. return this._sourceMesh.material;
  57086. },
  57087. enumerable: true,
  57088. configurable: true
  57089. });
  57090. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  57091. get: function () {
  57092. return this._sourceMesh.visibility;
  57093. },
  57094. enumerable: true,
  57095. configurable: true
  57096. });
  57097. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  57098. get: function () {
  57099. return this._sourceMesh.skeleton;
  57100. },
  57101. enumerable: true,
  57102. configurable: true
  57103. });
  57104. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  57105. get: function () {
  57106. return this._sourceMesh.renderingGroupId;
  57107. },
  57108. set: function (value) {
  57109. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  57110. return;
  57111. }
  57112. //no-op with warning
  57113. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  57114. },
  57115. enumerable: true,
  57116. configurable: true
  57117. });
  57118. /**
  57119. * Returns the total number of vertices (integer).
  57120. */
  57121. InstancedMesh.prototype.getTotalVertices = function () {
  57122. return this._sourceMesh.getTotalVertices();
  57123. };
  57124. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  57125. get: function () {
  57126. return this._sourceMesh;
  57127. },
  57128. enumerable: true,
  57129. configurable: true
  57130. });
  57131. /**
  57132. * Is this node ready to be used/rendered
  57133. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  57134. * @return {boolean} is it ready
  57135. */
  57136. InstancedMesh.prototype.isReady = function (completeCheck) {
  57137. if (completeCheck === void 0) { completeCheck = false; }
  57138. return this._sourceMesh.isReady(completeCheck, true);
  57139. };
  57140. /**
  57141. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  57142. */
  57143. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  57144. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  57145. };
  57146. /**
  57147. * Sets the vertex data of the mesh geometry for the requested `kind`.
  57148. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  57149. * The `data` are either a numeric array either a Float32Array.
  57150. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  57151. * 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).
  57152. * Note that a new underlying VertexBuffer object is created each call.
  57153. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  57154. *
  57155. * Possible `kind` values :
  57156. * - BABYLON.VertexBuffer.PositionKind
  57157. * - BABYLON.VertexBuffer.UVKind
  57158. * - BABYLON.VertexBuffer.UV2Kind
  57159. * - BABYLON.VertexBuffer.UV3Kind
  57160. * - BABYLON.VertexBuffer.UV4Kind
  57161. * - BABYLON.VertexBuffer.UV5Kind
  57162. * - BABYLON.VertexBuffer.UV6Kind
  57163. * - BABYLON.VertexBuffer.ColorKind
  57164. * - BABYLON.VertexBuffer.MatricesIndicesKind
  57165. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  57166. * - BABYLON.VertexBuffer.MatricesWeightsKind
  57167. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  57168. *
  57169. * Returns the Mesh.
  57170. */
  57171. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  57172. if (this.sourceMesh) {
  57173. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  57174. }
  57175. return this.sourceMesh;
  57176. };
  57177. /**
  57178. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  57179. * If the mesh has no geometry, it is simply returned as it is.
  57180. * The `data` are either a numeric array either a Float32Array.
  57181. * No new underlying VertexBuffer object is created.
  57182. * 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.
  57183. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  57184. *
  57185. * Possible `kind` values :
  57186. * - BABYLON.VertexBuffer.PositionKind
  57187. * - BABYLON.VertexBuffer.UVKind
  57188. * - BABYLON.VertexBuffer.UV2Kind
  57189. * - BABYLON.VertexBuffer.UV3Kind
  57190. * - BABYLON.VertexBuffer.UV4Kind
  57191. * - BABYLON.VertexBuffer.UV5Kind
  57192. * - BABYLON.VertexBuffer.UV6Kind
  57193. * - BABYLON.VertexBuffer.ColorKind
  57194. * - BABYLON.VertexBuffer.MatricesIndicesKind
  57195. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  57196. * - BABYLON.VertexBuffer.MatricesWeightsKind
  57197. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  57198. *
  57199. * Returns the Mesh.
  57200. */
  57201. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  57202. if (this.sourceMesh) {
  57203. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  57204. }
  57205. return this.sourceMesh;
  57206. };
  57207. /**
  57208. * Sets the mesh indices.
  57209. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  57210. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  57211. * This method creates a new index buffer each call.
  57212. * Returns the Mesh.
  57213. */
  57214. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  57215. if (totalVertices === void 0) { totalVertices = null; }
  57216. if (this.sourceMesh) {
  57217. this.sourceMesh.setIndices(indices, totalVertices);
  57218. }
  57219. return this.sourceMesh;
  57220. };
  57221. /**
  57222. * Boolean : True if the mesh owns the requested kind of data.
  57223. */
  57224. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  57225. return this._sourceMesh.isVerticesDataPresent(kind);
  57226. };
  57227. /**
  57228. * Returns an array of indices (IndicesArray).
  57229. */
  57230. InstancedMesh.prototype.getIndices = function () {
  57231. return this._sourceMesh.getIndices();
  57232. };
  57233. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  57234. get: function () {
  57235. return this._sourceMesh._positions;
  57236. },
  57237. enumerable: true,
  57238. configurable: true
  57239. });
  57240. /**
  57241. * Sets a new updated BoundingInfo to the mesh.
  57242. * Returns the mesh.
  57243. */
  57244. InstancedMesh.prototype.refreshBoundingInfo = function () {
  57245. var meshBB = this._sourceMesh.getBoundingInfo();
  57246. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  57247. this._updateBoundingInfo();
  57248. return this;
  57249. };
  57250. InstancedMesh.prototype._preActivate = function () {
  57251. if (this._currentLOD) {
  57252. this._currentLOD._preActivate();
  57253. }
  57254. return this;
  57255. };
  57256. InstancedMesh.prototype._activate = function (renderId) {
  57257. if (this._currentLOD) {
  57258. this._currentLOD._registerInstanceForRenderId(this, renderId);
  57259. }
  57260. return this;
  57261. };
  57262. /**
  57263. * Returns the current associated LOD AbstractMesh.
  57264. */
  57265. InstancedMesh.prototype.getLOD = function (camera) {
  57266. if (!camera) {
  57267. return this;
  57268. }
  57269. var boundingInfo = this.getBoundingInfo();
  57270. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  57271. if (this._currentLOD === this.sourceMesh) {
  57272. return this;
  57273. }
  57274. return this._currentLOD;
  57275. };
  57276. InstancedMesh.prototype._syncSubMeshes = function () {
  57277. this.releaseSubMeshes();
  57278. if (this._sourceMesh.subMeshes) {
  57279. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  57280. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  57281. }
  57282. }
  57283. return this;
  57284. };
  57285. InstancedMesh.prototype._generatePointsArray = function () {
  57286. return this._sourceMesh._generatePointsArray();
  57287. };
  57288. /**
  57289. * Creates a new InstancedMesh from the current mesh.
  57290. * - name (string) : the cloned mesh name
  57291. * - newParent (optional Node) : the optional Node to parent the clone to.
  57292. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  57293. *
  57294. * Returns the clone.
  57295. */
  57296. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  57297. var result = this._sourceMesh.createInstance(name);
  57298. // Deep copy
  57299. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  57300. // Bounding info
  57301. this.refreshBoundingInfo();
  57302. // Parent
  57303. if (newParent) {
  57304. result.parent = newParent;
  57305. }
  57306. if (!doNotCloneChildren) {
  57307. // Children
  57308. for (var index = 0; index < this.getScene().meshes.length; index++) {
  57309. var mesh = this.getScene().meshes[index];
  57310. if (mesh.parent === this) {
  57311. mesh.clone(mesh.name, result);
  57312. }
  57313. }
  57314. }
  57315. result.computeWorldMatrix(true);
  57316. return result;
  57317. };
  57318. /**
  57319. * Disposes the InstancedMesh.
  57320. * Returns nothing.
  57321. */
  57322. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  57323. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  57324. // Remove from mesh
  57325. var index = this._sourceMesh.instances.indexOf(this);
  57326. this._sourceMesh.instances.splice(index, 1);
  57327. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  57328. };
  57329. return InstancedMesh;
  57330. }(BABYLON.AbstractMesh));
  57331. BABYLON.InstancedMesh = InstancedMesh;
  57332. })(BABYLON || (BABYLON = {}));
  57333. //# sourceMappingURL=babylon.instancedMesh.js.map
  57334. "use strict";
  57335. var BABYLON;
  57336. (function (BABYLON) {
  57337. var LinesMesh = /** @class */ (function (_super) {
  57338. __extends(LinesMesh, _super);
  57339. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  57340. if (scene === void 0) { scene = null; }
  57341. if (parent === void 0) { parent = null; }
  57342. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  57343. _this.useVertexColor = useVertexColor;
  57344. _this.useVertexAlpha = useVertexAlpha;
  57345. _this.color = new BABYLON.Color3(1, 1, 1);
  57346. _this.alpha = 1;
  57347. if (source) {
  57348. _this.color = source.color.clone();
  57349. _this.alpha = source.alpha;
  57350. _this.useVertexColor = source.useVertexColor;
  57351. _this.useVertexAlpha = source.useVertexAlpha;
  57352. }
  57353. _this._intersectionThreshold = 0.1;
  57354. var defines = [];
  57355. var options = {
  57356. attributes: [BABYLON.VertexBuffer.PositionKind],
  57357. uniforms: ["world", "viewProjection"],
  57358. needAlphaBlending: true,
  57359. defines: defines
  57360. };
  57361. if (useVertexAlpha === false) {
  57362. options.needAlphaBlending = false;
  57363. }
  57364. if (!useVertexColor) {
  57365. options.uniforms.push("color");
  57366. }
  57367. else {
  57368. options.defines.push("#define VERTEXCOLOR");
  57369. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  57370. }
  57371. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  57372. return _this;
  57373. }
  57374. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  57375. /**
  57376. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  57377. * This margin is expressed in world space coordinates, so its value may vary.
  57378. * Default value is 0.1
  57379. * @returns the intersection Threshold value.
  57380. */
  57381. get: function () {
  57382. return this._intersectionThreshold;
  57383. },
  57384. /**
  57385. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  57386. * This margin is expressed in world space coordinates, so its value may vary.
  57387. * @param value the new threshold to apply
  57388. */
  57389. set: function (value) {
  57390. if (this._intersectionThreshold === value) {
  57391. return;
  57392. }
  57393. this._intersectionThreshold = value;
  57394. if (this.geometry) {
  57395. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  57396. }
  57397. },
  57398. enumerable: true,
  57399. configurable: true
  57400. });
  57401. /**
  57402. * Returns the string "LineMesh"
  57403. */
  57404. LinesMesh.prototype.getClassName = function () {
  57405. return "LinesMesh";
  57406. };
  57407. Object.defineProperty(LinesMesh.prototype, "material", {
  57408. get: function () {
  57409. return this._colorShader;
  57410. },
  57411. set: function (value) {
  57412. // Do nothing
  57413. },
  57414. enumerable: true,
  57415. configurable: true
  57416. });
  57417. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  57418. get: function () {
  57419. return false;
  57420. },
  57421. enumerable: true,
  57422. configurable: true
  57423. });
  57424. LinesMesh.prototype.createInstance = function (name) {
  57425. throw new Error("LinesMeshes do not support createInstance.");
  57426. };
  57427. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  57428. if (!this._geometry) {
  57429. return this;
  57430. }
  57431. // VBOs
  57432. this._geometry._bind(this._colorShader.getEffect());
  57433. // Color
  57434. if (!this.useVertexColor) {
  57435. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  57436. }
  57437. return this;
  57438. };
  57439. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  57440. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  57441. return this;
  57442. }
  57443. var engine = this.getScene().getEngine();
  57444. // Draw order
  57445. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  57446. return this;
  57447. };
  57448. LinesMesh.prototype.dispose = function (doNotRecurse) {
  57449. this._colorShader.dispose();
  57450. _super.prototype.dispose.call(this, doNotRecurse);
  57451. };
  57452. /**
  57453. * Returns a new LineMesh object cloned from the current one.
  57454. */
  57455. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  57456. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  57457. };
  57458. return LinesMesh;
  57459. }(BABYLON.Mesh));
  57460. BABYLON.LinesMesh = LinesMesh;
  57461. })(BABYLON || (BABYLON = {}));
  57462. //# sourceMappingURL=babylon.linesMesh.js.map
  57463. "use strict";
  57464. var BABYLON;
  57465. (function (BABYLON) {
  57466. var MeshBuilder = /** @class */ (function () {
  57467. function MeshBuilder() {
  57468. }
  57469. MeshBuilder.updateSideOrientation = function (orientation) {
  57470. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  57471. return BABYLON.Mesh.DOUBLESIDE;
  57472. }
  57473. if (orientation === undefined || orientation === null) {
  57474. return BABYLON.Mesh.FRONTSIDE;
  57475. }
  57476. return orientation;
  57477. };
  57478. /**
  57479. * Creates a box mesh.
  57480. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  57481. * The parameter `size` sets the size (float) of each box side (default 1).
  57482. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  57483. * 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).
  57484. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57485. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57486. * 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).
  57487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57489. */
  57490. MeshBuilder.CreateBox = function (name, options, scene) {
  57491. if (scene === void 0) { scene = null; }
  57492. var box = new BABYLON.Mesh(name, scene);
  57493. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57494. box._originalBuilderSideOrientation = options.sideOrientation;
  57495. var vertexData = BABYLON.VertexData.CreateBox(options);
  57496. vertexData.applyToMesh(box, options.updatable);
  57497. return box;
  57498. };
  57499. /**
  57500. * Creates a sphere mesh.
  57501. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  57502. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  57503. * 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`).
  57504. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  57505. * 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
  57506. * 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).
  57507. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57508. * 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).
  57509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57511. */
  57512. MeshBuilder.CreateSphere = function (name, options, scene) {
  57513. var sphere = new BABYLON.Mesh(name, scene);
  57514. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57515. sphere._originalBuilderSideOrientation = options.sideOrientation;
  57516. var vertexData = BABYLON.VertexData.CreateSphere(options);
  57517. vertexData.applyToMesh(sphere, options.updatable);
  57518. return sphere;
  57519. };
  57520. /**
  57521. * Creates a plane polygonal mesh. By default, this is a disc.
  57522. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  57523. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  57524. * 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.
  57525. * 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
  57526. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57527. * 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).
  57528. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57529. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57530. */
  57531. MeshBuilder.CreateDisc = function (name, options, scene) {
  57532. if (scene === void 0) { scene = null; }
  57533. var disc = new BABYLON.Mesh(name, scene);
  57534. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57535. disc._originalBuilderSideOrientation = options.sideOrientation;
  57536. var vertexData = BABYLON.VertexData.CreateDisc(options);
  57537. vertexData.applyToMesh(disc, options.updatable);
  57538. return disc;
  57539. };
  57540. /**
  57541. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  57542. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  57543. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  57544. * 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`).
  57545. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  57546. * 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.
  57547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57548. * 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).
  57549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57551. */
  57552. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  57553. var sphere = new BABYLON.Mesh(name, scene);
  57554. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57555. sphere._originalBuilderSideOrientation = options.sideOrientation;
  57556. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  57557. vertexData.applyToMesh(sphere, options.updatable);
  57558. return sphere;
  57559. };
  57560. ;
  57561. /**
  57562. * Creates a ribbon mesh.
  57563. * 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.
  57564. *
  57565. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  57566. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  57567. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  57568. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  57569. * 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.
  57570. * 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.
  57571. * 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
  57572. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57573. * 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).
  57574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57575. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57576. * 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.
  57577. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  57578. * 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
  57579. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  57580. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  57581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57582. */
  57583. MeshBuilder.CreateRibbon = function (name, options, scene) {
  57584. if (scene === void 0) { scene = null; }
  57585. var pathArray = options.pathArray;
  57586. var closeArray = options.closeArray;
  57587. var closePath = options.closePath;
  57588. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57589. var instance = options.instance;
  57590. var updatable = options.updatable;
  57591. if (instance) {
  57592. // positionFunction : ribbon case
  57593. // only pathArray and sideOrientation parameters are taken into account for positions update
  57594. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  57595. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  57596. var positionFunction = function (positions) {
  57597. var minlg = pathArray[0].length;
  57598. var i = 0;
  57599. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  57600. for (var si = 1; si <= ns; si++) {
  57601. for (var p = 0; p < pathArray.length; p++) {
  57602. var path = pathArray[p];
  57603. var l = path.length;
  57604. minlg = (minlg < l) ? minlg : l;
  57605. var j = 0;
  57606. while (j < minlg) {
  57607. positions[i] = path[j].x;
  57608. positions[i + 1] = path[j].y;
  57609. positions[i + 2] = path[j].z;
  57610. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  57611. BABYLON.Tmp.Vector3[0].x = path[j].x;
  57612. }
  57613. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  57614. BABYLON.Tmp.Vector3[1].x = path[j].x;
  57615. }
  57616. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  57617. BABYLON.Tmp.Vector3[0].y = path[j].y;
  57618. }
  57619. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  57620. BABYLON.Tmp.Vector3[1].y = path[j].y;
  57621. }
  57622. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  57623. BABYLON.Tmp.Vector3[0].z = path[j].z;
  57624. }
  57625. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  57626. BABYLON.Tmp.Vector3[1].z = path[j].z;
  57627. }
  57628. j++;
  57629. i += 3;
  57630. }
  57631. if (instance._closePath) {
  57632. positions[i] = path[0].x;
  57633. positions[i + 1] = path[0].y;
  57634. positions[i + 2] = path[0].z;
  57635. i += 3;
  57636. }
  57637. }
  57638. }
  57639. };
  57640. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57641. positionFunction(positions);
  57642. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  57643. instance._boundingInfo.update(instance._worldMatrix);
  57644. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  57645. if (options.colors) {
  57646. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57647. for (var c = 0; c < options.colors.length; c++) {
  57648. colors[c * 4] = options.colors[c].r;
  57649. colors[c * 4 + 1] = options.colors[c].g;
  57650. colors[c * 4 + 2] = options.colors[c].b;
  57651. colors[c * 4 + 3] = options.colors[c].a;
  57652. }
  57653. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  57654. }
  57655. if (options.uvs) {
  57656. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57657. for (var i = 0; i < options.uvs.length; i++) {
  57658. uvs[i * 2] = options.uvs[i].x;
  57659. uvs[i * 2 + 1] = options.uvs[i].y;
  57660. }
  57661. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  57662. }
  57663. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  57664. var indices = instance.getIndices();
  57665. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57666. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  57667. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  57668. if (instance._closePath) {
  57669. var indexFirst = 0;
  57670. var indexLast = 0;
  57671. for (var p = 0; p < pathArray.length; p++) {
  57672. indexFirst = instance._idx[p] * 3;
  57673. if (p + 1 < pathArray.length) {
  57674. indexLast = (instance._idx[p + 1] - 1) * 3;
  57675. }
  57676. else {
  57677. indexLast = normals.length - 3;
  57678. }
  57679. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  57680. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  57681. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  57682. normals[indexLast] = normals[indexFirst];
  57683. normals[indexLast + 1] = normals[indexFirst + 1];
  57684. normals[indexLast + 2] = normals[indexFirst + 2];
  57685. }
  57686. }
  57687. if (!(instance.areNormalsFrozen)) {
  57688. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  57689. }
  57690. }
  57691. return instance;
  57692. }
  57693. else {
  57694. var ribbon = new BABYLON.Mesh(name, scene);
  57695. ribbon._originalBuilderSideOrientation = sideOrientation;
  57696. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  57697. if (closePath) {
  57698. ribbon._idx = vertexData._idx;
  57699. }
  57700. ribbon._closePath = closePath;
  57701. ribbon._closeArray = closeArray;
  57702. vertexData.applyToMesh(ribbon, updatable);
  57703. return ribbon;
  57704. }
  57705. };
  57706. /**
  57707. * Creates a cylinder or a cone mesh.
  57708. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  57709. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  57710. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  57711. * 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.
  57712. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  57713. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  57714. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  57715. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  57716. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  57717. * 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).
  57718. * 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
  57719. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  57720. * 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
  57721. * 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.
  57722. * If `enclose` is false, a ring surface is one element.
  57723. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  57724. * 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
  57725. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57726. * 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).
  57727. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57729. */
  57730. MeshBuilder.CreateCylinder = function (name, options, scene) {
  57731. var cylinder = new BABYLON.Mesh(name, scene);
  57732. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57733. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  57734. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  57735. vertexData.applyToMesh(cylinder, options.updatable);
  57736. return cylinder;
  57737. };
  57738. /**
  57739. * Creates a torus mesh.
  57740. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  57741. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  57742. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  57743. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  57744. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57745. * 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).
  57746. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57748. */
  57749. MeshBuilder.CreateTorus = function (name, options, scene) {
  57750. var torus = new BABYLON.Mesh(name, scene);
  57751. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57752. torus._originalBuilderSideOrientation = options.sideOrientation;
  57753. var vertexData = BABYLON.VertexData.CreateTorus(options);
  57754. vertexData.applyToMesh(torus, options.updatable);
  57755. return torus;
  57756. };
  57757. /**
  57758. * Creates a torus knot mesh.
  57759. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  57760. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  57761. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  57762. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  57763. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  57764. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57765. * 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).
  57766. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57768. */
  57769. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  57770. var torusKnot = new BABYLON.Mesh(name, scene);
  57771. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57772. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  57773. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  57774. vertexData.applyToMesh(torusKnot, options.updatable);
  57775. return torusKnot;
  57776. };
  57777. /**
  57778. * Creates a line system mesh.
  57779. * A line system is a pool of many lines gathered in a single mesh.
  57780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  57781. * 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.
  57782. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  57783. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  57784. * 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
  57785. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  57786. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  57787. * 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
  57788. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  57789. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57790. */
  57791. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  57792. var instance = options.instance;
  57793. var lines = options.lines;
  57794. var colors = options.colors;
  57795. if (instance) {
  57796. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57797. var vertexColor;
  57798. var lineColors;
  57799. if (colors) {
  57800. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57801. }
  57802. var i = 0;
  57803. var c = 0;
  57804. for (var l = 0; l < lines.length; l++) {
  57805. var points = lines[l];
  57806. for (var p = 0; p < points.length; p++) {
  57807. positions[i] = points[p].x;
  57808. positions[i + 1] = points[p].y;
  57809. positions[i + 2] = points[p].z;
  57810. if (colors && vertexColor) {
  57811. lineColors = colors[l];
  57812. vertexColor[c] = lineColors[p].r;
  57813. vertexColor[c + 1] = lineColors[p].g;
  57814. vertexColor[c + 2] = lineColors[p].b;
  57815. vertexColor[c + 3] = lineColors[p].a;
  57816. c += 4;
  57817. }
  57818. i += 3;
  57819. }
  57820. }
  57821. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  57822. if (colors && vertexColor) {
  57823. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  57824. }
  57825. return instance;
  57826. }
  57827. // line system creation
  57828. var useVertexColor = (colors) ? true : false;
  57829. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  57830. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  57831. vertexData.applyToMesh(lineSystem, options.updatable);
  57832. return lineSystem;
  57833. };
  57834. /**
  57835. * Creates a line mesh.
  57836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  57837. * 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.
  57838. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  57839. * The parameter `points` is an array successive Vector3.
  57840. * 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
  57841. * The optional parameter `colors` is an array of successive Color4, one per line point.
  57842. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  57843. * When updating an instance, remember that only point positions can change, not the number of points.
  57844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57845. */
  57846. MeshBuilder.CreateLines = function (name, options, scene) {
  57847. if (scene === void 0) { scene = null; }
  57848. var colors = (options.colors) ? [options.colors] : null;
  57849. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  57850. return lines;
  57851. };
  57852. /**
  57853. * Creates a dashed line mesh.
  57854. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  57855. * 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.
  57856. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  57857. * The parameter `points` is an array successive Vector3.
  57858. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  57859. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  57860. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  57861. * 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
  57862. * When updating an instance, remember that only point positions can change, not the number of points.
  57863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57864. */
  57865. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  57866. if (scene === void 0) { scene = null; }
  57867. var points = options.points;
  57868. var instance = options.instance;
  57869. var gapSize = options.gapSize || 1;
  57870. var dashSize = options.dashSize || 3;
  57871. if (instance) {
  57872. var positionFunction = function (positions) {
  57873. var curvect = BABYLON.Vector3.Zero();
  57874. var nbSeg = positions.length / 6;
  57875. var lg = 0;
  57876. var nb = 0;
  57877. var shft = 0;
  57878. var dashshft = 0;
  57879. var curshft = 0;
  57880. var p = 0;
  57881. var i = 0;
  57882. var j = 0;
  57883. for (i = 0; i < points.length - 1; i++) {
  57884. points[i + 1].subtractToRef(points[i], curvect);
  57885. lg += curvect.length();
  57886. }
  57887. shft = lg / nbSeg;
  57888. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  57889. for (i = 0; i < points.length - 1; i++) {
  57890. points[i + 1].subtractToRef(points[i], curvect);
  57891. nb = Math.floor(curvect.length() / shft);
  57892. curvect.normalize();
  57893. j = 0;
  57894. while (j < nb && p < positions.length) {
  57895. curshft = shft * j;
  57896. positions[p] = points[i].x + curshft * curvect.x;
  57897. positions[p + 1] = points[i].y + curshft * curvect.y;
  57898. positions[p + 2] = points[i].z + curshft * curvect.z;
  57899. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  57900. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  57901. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  57902. p += 6;
  57903. j++;
  57904. }
  57905. }
  57906. while (p < positions.length) {
  57907. positions[p] = points[i].x;
  57908. positions[p + 1] = points[i].y;
  57909. positions[p + 2] = points[i].z;
  57910. p += 3;
  57911. }
  57912. };
  57913. instance.updateMeshPositions(positionFunction, false);
  57914. return instance;
  57915. }
  57916. // dashed lines creation
  57917. var dashedLines = new BABYLON.LinesMesh(name, scene);
  57918. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  57919. vertexData.applyToMesh(dashedLines, options.updatable);
  57920. dashedLines.dashSize = dashSize;
  57921. dashedLines.gapSize = gapSize;
  57922. return dashedLines;
  57923. };
  57924. /**
  57925. * Creates an extruded shape mesh.
  57926. * 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.
  57927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  57928. *
  57929. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57930. * 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
  57931. * extruded along the Z axis.
  57932. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57933. * 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.
  57934. * The parameter `scale` (float, default 1) is the value to scale the shape.
  57935. * 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
  57936. * 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
  57937. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57939. * 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).
  57940. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57941. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57943. */
  57944. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  57945. if (scene === void 0) { scene = null; }
  57946. var path = options.path;
  57947. var shape = options.shape;
  57948. var scale = options.scale || 1;
  57949. var rotation = options.rotation || 0;
  57950. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57951. var updatable = options.updatable;
  57952. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57953. var instance = options.instance || null;
  57954. var invertUV = options.invertUV || false;
  57955. 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);
  57956. };
  57957. /**
  57958. * Creates an custom extruded shape mesh.
  57959. * 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.
  57960. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  57961. *
  57962. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57963. * 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
  57964. * extruded along the Z axis.
  57965. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57966. * 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
  57967. * and the distance of this point from the begining of the path :
  57968. * ```javascript
  57969. * var rotationFunction = function(i, distance) {
  57970. * // do things
  57971. * return rotationValue; }
  57972. * ```
  57973. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  57974. * 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
  57975. * and the distance of this point from the begining of the path :
  57976. * ```javascript
  57977. * var scaleFunction = function(i, distance) {
  57978. * // do things
  57979. * return scaleValue;}
  57980. * ```
  57981. * It must returns a float value that will be the scale value applied to the shape on each path point.
  57982. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  57983. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  57984. * 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
  57985. * 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
  57986. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57987. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57988. * 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).
  57989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57990. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57991. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57992. */
  57993. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  57994. var path = options.path;
  57995. var shape = options.shape;
  57996. var scaleFunction = options.scaleFunction || (function () { return 1; });
  57997. var rotationFunction = options.rotationFunction || (function () { return 0; });
  57998. var ribbonCloseArray = options.ribbonCloseArray || false;
  57999. var ribbonClosePath = options.ribbonClosePath || false;
  58000. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  58001. var updatable = options.updatable;
  58002. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58003. var instance = options.instance;
  58004. var invertUV = options.invertUV || false;
  58005. 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);
  58006. };
  58007. /**
  58008. * Creates lathe mesh.
  58009. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  58010. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  58011. *
  58012. * 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
  58013. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  58014. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  58015. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  58016. * 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.
  58017. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  58018. * 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
  58019. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58020. * 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).
  58021. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58022. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  58023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58024. */
  58025. MeshBuilder.CreateLathe = function (name, options, scene) {
  58026. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  58027. var closed = (options.closed === undefined) ? true : options.closed;
  58028. var shape = options.shape;
  58029. var radius = options.radius || 1;
  58030. var tessellation = options.tessellation || 64;
  58031. var updatable = options.updatable;
  58032. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58033. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  58034. var pi2 = Math.PI * 2;
  58035. var paths = new Array();
  58036. var invertUV = options.invertUV || false;
  58037. var i = 0;
  58038. var p = 0;
  58039. var step = pi2 / tessellation * arc;
  58040. var rotated;
  58041. var path = new Array();
  58042. ;
  58043. for (i = 0; i <= tessellation; i++) {
  58044. var path = [];
  58045. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  58046. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  58047. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  58048. }
  58049. for (p = 0; p < shape.length; p++) {
  58050. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  58051. path.push(rotated);
  58052. }
  58053. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  58054. 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));
  58055. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  58056. }
  58057. paths.push(path);
  58058. }
  58059. // lathe ribbon
  58060. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  58061. return lathe;
  58062. };
  58063. /**
  58064. * Creates a plane mesh.
  58065. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  58066. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  58067. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  58068. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  58069. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58070. * 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).
  58071. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58073. */
  58074. MeshBuilder.CreatePlane = function (name, options, scene) {
  58075. var plane = new BABYLON.Mesh(name, scene);
  58076. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58077. plane._originalBuilderSideOrientation = options.sideOrientation;
  58078. var vertexData = BABYLON.VertexData.CreatePlane(options);
  58079. vertexData.applyToMesh(plane, options.updatable);
  58080. if (options.sourcePlane) {
  58081. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  58082. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  58083. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  58084. plane.rotate(vectorProduct, product);
  58085. }
  58086. return plane;
  58087. };
  58088. /**
  58089. * Creates a ground mesh.
  58090. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  58091. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  58092. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  58093. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58094. */
  58095. MeshBuilder.CreateGround = function (name, options, scene) {
  58096. var ground = new BABYLON.GroundMesh(name, scene);
  58097. ground._setReady(false);
  58098. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  58099. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  58100. ground._width = options.width || 1;
  58101. ground._height = options.height || 1;
  58102. ground._maxX = ground._width / 2;
  58103. ground._maxZ = ground._height / 2;
  58104. ground._minX = -ground._maxX;
  58105. ground._minZ = -ground._maxZ;
  58106. var vertexData = BABYLON.VertexData.CreateGround(options);
  58107. vertexData.applyToMesh(ground, options.updatable);
  58108. ground._setReady(true);
  58109. return ground;
  58110. };
  58111. /**
  58112. * Creates a tiled ground mesh.
  58113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  58114. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  58115. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  58116. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  58117. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  58118. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  58119. * numbers of subdivisions on the ground width and height of each tile.
  58120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58121. */
  58122. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  58123. var tiledGround = new BABYLON.Mesh(name, scene);
  58124. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  58125. vertexData.applyToMesh(tiledGround, options.updatable);
  58126. return tiledGround;
  58127. };
  58128. /**
  58129. * Creates a ground mesh from a height map.
  58130. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  58131. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  58132. * The parameter `url` sets the URL of the height map image resource.
  58133. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  58134. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  58135. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  58136. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  58137. * 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.
  58138. * 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).
  58139. * This function is passed the newly built mesh :
  58140. * ```javascript
  58141. * function(mesh) { // do things
  58142. * return; }
  58143. * ```
  58144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58145. */
  58146. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  58147. var width = options.width || 10.0;
  58148. var height = options.height || 10.0;
  58149. var subdivisions = options.subdivisions || 1 | 0;
  58150. var minHeight = options.minHeight || 0.0;
  58151. var maxHeight = options.maxHeight || 1.0;
  58152. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  58153. var updatable = options.updatable;
  58154. var onReady = options.onReady;
  58155. var ground = new BABYLON.GroundMesh(name, scene);
  58156. ground._subdivisionsX = subdivisions;
  58157. ground._subdivisionsY = subdivisions;
  58158. ground._width = width;
  58159. ground._height = height;
  58160. ground._maxX = ground._width / 2.0;
  58161. ground._maxZ = ground._height / 2.0;
  58162. ground._minX = -ground._maxX;
  58163. ground._minZ = -ground._maxZ;
  58164. ground._setReady(false);
  58165. var onload = function (img) {
  58166. // Getting height map data
  58167. var canvas = document.createElement("canvas");
  58168. var context = canvas.getContext("2d");
  58169. if (!context) {
  58170. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  58171. }
  58172. if (scene.isDisposed) {
  58173. return;
  58174. }
  58175. var bufferWidth = img.width;
  58176. var bufferHeight = img.height;
  58177. canvas.width = bufferWidth;
  58178. canvas.height = bufferHeight;
  58179. context.drawImage(img, 0, 0);
  58180. // Create VertexData from map data
  58181. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  58182. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  58183. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  58184. width: width, height: height,
  58185. subdivisions: subdivisions,
  58186. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  58187. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  58188. });
  58189. vertexData.applyToMesh(ground, updatable);
  58190. //execute ready callback, if set
  58191. if (onReady) {
  58192. onReady(ground);
  58193. }
  58194. ground._setReady(true);
  58195. };
  58196. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  58197. return ground;
  58198. };
  58199. /**
  58200. * Creates a polygon mesh.
  58201. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  58202. * 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.
  58203. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58205. * 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).
  58206. * Remember you can only change the shape positions, not their number when updating a polygon.
  58207. */
  58208. MeshBuilder.CreatePolygon = function (name, options, scene) {
  58209. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58210. var shape = options.shape;
  58211. var holes = options.holes || [];
  58212. var depth = options.depth || 0;
  58213. var contours = [];
  58214. var hole = [];
  58215. for (var i = 0; i < shape.length; i++) {
  58216. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  58217. }
  58218. var epsilon = 0.00000001;
  58219. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  58220. contours.pop();
  58221. }
  58222. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  58223. for (var hNb = 0; hNb < holes.length; hNb++) {
  58224. hole = [];
  58225. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  58226. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  58227. }
  58228. polygonTriangulation.addHole(hole);
  58229. }
  58230. var polygon = polygonTriangulation.build(options.updatable, depth);
  58231. polygon._originalBuilderSideOrientation = options.sideOrientation;
  58232. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  58233. vertexData.applyToMesh(polygon, options.updatable);
  58234. return polygon;
  58235. };
  58236. ;
  58237. /**
  58238. * Creates an extruded polygon mesh, with depth in the Y direction.
  58239. * 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).
  58240. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  58241. */
  58242. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  58243. return MeshBuilder.CreatePolygon(name, options, scene);
  58244. };
  58245. ;
  58246. /**
  58247. * Creates a tube mesh.
  58248. * 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.
  58249. *
  58250. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  58251. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  58252. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  58253. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  58254. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  58255. * 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.
  58256. * It must return a radius value (positive float) :
  58257. * ```javascript
  58258. * var radiusFunction = function(i, distance) {
  58259. * // do things
  58260. * return radius; }
  58261. * ```
  58262. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  58263. * 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
  58264. * 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
  58265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58266. * 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).
  58267. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58268. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  58269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58270. */
  58271. MeshBuilder.CreateTube = function (name, options, scene) {
  58272. var path = options.path;
  58273. var instance = options.instance;
  58274. var radius = 1.0;
  58275. if (instance) {
  58276. radius = instance.radius;
  58277. }
  58278. if (options.radius !== undefined) {
  58279. radius = options.radius;
  58280. }
  58281. ;
  58282. var tessellation = options.tessellation || 64 | 0;
  58283. var radiusFunction = options.radiusFunction || null;
  58284. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  58285. var invertUV = options.invertUV || false;
  58286. var updatable = options.updatable;
  58287. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58288. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  58289. // tube geometry
  58290. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  58291. var tangents = path3D.getTangents();
  58292. var normals = path3D.getNormals();
  58293. var distances = path3D.getDistances();
  58294. var pi2 = Math.PI * 2;
  58295. var step = pi2 / tessellation * arc;
  58296. var returnRadius = function () { return radius; };
  58297. var radiusFunctionFinal = radiusFunction || returnRadius;
  58298. var circlePath;
  58299. var rad;
  58300. var normal;
  58301. var rotated;
  58302. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  58303. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  58304. for (var i = 0; i < path.length; i++) {
  58305. rad = radiusFunctionFinal(i, distances[i]); // current radius
  58306. circlePath = Array(); // current circle array
  58307. normal = normals[i]; // current normal
  58308. for (var t = 0; t < tessellation; t++) {
  58309. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  58310. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  58311. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  58312. rotated.scaleInPlace(rad).addInPlace(path[i]);
  58313. circlePath[t] = rotated;
  58314. }
  58315. circlePaths[index] = circlePath;
  58316. index++;
  58317. }
  58318. // cap
  58319. var capPath = function (nbPoints, pathIndex) {
  58320. var pointCap = Array();
  58321. for (var i = 0; i < nbPoints; i++) {
  58322. pointCap.push(path[pathIndex]);
  58323. }
  58324. return pointCap;
  58325. };
  58326. switch (cap) {
  58327. case BABYLON.Mesh.NO_CAP:
  58328. break;
  58329. case BABYLON.Mesh.CAP_START:
  58330. circlePaths[0] = capPath(tessellation, 0);
  58331. circlePaths[1] = circlePaths[2].slice(0);
  58332. break;
  58333. case BABYLON.Mesh.CAP_END:
  58334. circlePaths[index] = circlePaths[index - 1].slice(0);
  58335. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  58336. break;
  58337. case BABYLON.Mesh.CAP_ALL:
  58338. circlePaths[0] = capPath(tessellation, 0);
  58339. circlePaths[1] = circlePaths[2].slice(0);
  58340. circlePaths[index] = circlePaths[index - 1].slice(0);
  58341. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  58342. break;
  58343. default:
  58344. break;
  58345. }
  58346. return circlePaths;
  58347. };
  58348. var path3D;
  58349. var pathArray;
  58350. if (instance) {
  58351. var arc = options.arc || instance.arc;
  58352. path3D = (instance.path3D).update(path);
  58353. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  58354. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  58355. instance.path3D = path3D;
  58356. instance.pathArray = pathArray;
  58357. instance.arc = arc;
  58358. instance.radius = radius;
  58359. return instance;
  58360. }
  58361. // tube creation
  58362. path3D = new BABYLON.Path3D(path);
  58363. var newPathArray = new Array();
  58364. cap = (cap < 0 || cap > 3) ? 0 : cap;
  58365. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  58366. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  58367. tube.pathArray = pathArray;
  58368. tube.path3D = path3D;
  58369. tube.tessellation = tessellation;
  58370. tube.cap = cap;
  58371. tube.arc = options.arc;
  58372. tube.radius = radius;
  58373. return tube;
  58374. };
  58375. /**
  58376. * Creates a polyhedron mesh.
  58377. *
  58378. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  58379. * 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
  58380. * to choose the wanted type.
  58381. * The parameter `size` (positive float, default 1) sets the polygon size.
  58382. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  58383. * 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`.
  58384. * 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
  58385. * 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)`).
  58386. * 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
  58387. * 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.
  58388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58389. * 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).
  58390. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58392. */
  58393. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  58394. var polyhedron = new BABYLON.Mesh(name, scene);
  58395. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58396. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  58397. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  58398. vertexData.applyToMesh(polyhedron, options.updatable);
  58399. return polyhedron;
  58400. };
  58401. /**
  58402. * Creates a decal mesh.
  58403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  58404. * 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.
  58405. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  58406. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  58407. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  58408. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  58409. */
  58410. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  58411. var indices = sourceMesh.getIndices();
  58412. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58413. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58414. var position = options.position || BABYLON.Vector3.Zero();
  58415. var normal = options.normal || BABYLON.Vector3.Up();
  58416. var size = options.size || BABYLON.Vector3.One();
  58417. var angle = options.angle || 0;
  58418. // Getting correct rotation
  58419. if (!normal) {
  58420. var target = new BABYLON.Vector3(0, 0, 1);
  58421. var camera = sourceMesh.getScene().activeCamera;
  58422. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  58423. normal = camera.globalPosition.subtract(cameraWorldTarget);
  58424. }
  58425. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  58426. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  58427. var pitch = Math.atan2(normal.y, len);
  58428. // Matrix
  58429. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  58430. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  58431. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  58432. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  58433. var vertexData = new BABYLON.VertexData();
  58434. vertexData.indices = [];
  58435. vertexData.positions = [];
  58436. vertexData.normals = [];
  58437. vertexData.uvs = [];
  58438. var currentVertexDataIndex = 0;
  58439. var extractDecalVector3 = function (indexId) {
  58440. var result = new BABYLON.PositionNormalVertex();
  58441. if (!indices || !positions || !normals) {
  58442. return result;
  58443. }
  58444. var vertexId = indices[indexId];
  58445. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  58446. // Send vector to decal local world
  58447. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  58448. // Get normal
  58449. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  58450. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  58451. return result;
  58452. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  58453. var clip = function (vertices, axis) {
  58454. if (vertices.length === 0) {
  58455. return vertices;
  58456. }
  58457. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  58458. var clipVertices = function (v0, v1) {
  58459. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  58460. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  58461. };
  58462. var result = new Array();
  58463. for (var index = 0; index < vertices.length; index += 3) {
  58464. var v1Out;
  58465. var v2Out;
  58466. var v3Out;
  58467. var total = 0;
  58468. var nV1 = null;
  58469. var nV2 = null;
  58470. var nV3 = null;
  58471. var nV4 = null;
  58472. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  58473. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  58474. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  58475. v1Out = d1 > 0;
  58476. v2Out = d2 > 0;
  58477. v3Out = d3 > 0;
  58478. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  58479. switch (total) {
  58480. case 0:
  58481. result.push(vertices[index]);
  58482. result.push(vertices[index + 1]);
  58483. result.push(vertices[index + 2]);
  58484. break;
  58485. case 1:
  58486. if (v1Out) {
  58487. nV1 = vertices[index + 1];
  58488. nV2 = vertices[index + 2];
  58489. nV3 = clipVertices(vertices[index], nV1);
  58490. nV4 = clipVertices(vertices[index], nV2);
  58491. }
  58492. if (v2Out) {
  58493. nV1 = vertices[index];
  58494. nV2 = vertices[index + 2];
  58495. nV3 = clipVertices(vertices[index + 1], nV1);
  58496. nV4 = clipVertices(vertices[index + 1], nV2);
  58497. result.push(nV3);
  58498. result.push(nV2.clone());
  58499. result.push(nV1.clone());
  58500. result.push(nV2.clone());
  58501. result.push(nV3.clone());
  58502. result.push(nV4);
  58503. break;
  58504. }
  58505. if (v3Out) {
  58506. nV1 = vertices[index];
  58507. nV2 = vertices[index + 1];
  58508. nV3 = clipVertices(vertices[index + 2], nV1);
  58509. nV4 = clipVertices(vertices[index + 2], nV2);
  58510. }
  58511. if (nV1 && nV2 && nV3 && nV4) {
  58512. result.push(nV1.clone());
  58513. result.push(nV2.clone());
  58514. result.push(nV3);
  58515. result.push(nV4);
  58516. result.push(nV3.clone());
  58517. result.push(nV2.clone());
  58518. }
  58519. break;
  58520. case 2:
  58521. if (!v1Out) {
  58522. nV1 = vertices[index].clone();
  58523. nV2 = clipVertices(nV1, vertices[index + 1]);
  58524. nV3 = clipVertices(nV1, vertices[index + 2]);
  58525. result.push(nV1);
  58526. result.push(nV2);
  58527. result.push(nV3);
  58528. }
  58529. if (!v2Out) {
  58530. nV1 = vertices[index + 1].clone();
  58531. nV2 = clipVertices(nV1, vertices[index + 2]);
  58532. nV3 = clipVertices(nV1, vertices[index]);
  58533. result.push(nV1);
  58534. result.push(nV2);
  58535. result.push(nV3);
  58536. }
  58537. if (!v3Out) {
  58538. nV1 = vertices[index + 2].clone();
  58539. nV2 = clipVertices(nV1, vertices[index]);
  58540. nV3 = clipVertices(nV1, vertices[index + 1]);
  58541. result.push(nV1);
  58542. result.push(nV2);
  58543. result.push(nV3);
  58544. }
  58545. break;
  58546. case 3:
  58547. break;
  58548. }
  58549. }
  58550. return result;
  58551. };
  58552. for (var index = 0; index < indices.length; index += 3) {
  58553. var faceVertices = new Array();
  58554. faceVertices.push(extractDecalVector3(index));
  58555. faceVertices.push(extractDecalVector3(index + 1));
  58556. faceVertices.push(extractDecalVector3(index + 2));
  58557. // Clip
  58558. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  58559. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  58560. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  58561. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  58562. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  58563. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  58564. if (faceVertices.length === 0) {
  58565. continue;
  58566. }
  58567. // Add UVs and get back to world
  58568. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  58569. var vertex = faceVertices[vIndex];
  58570. //TODO check for Int32Array | Uint32Array | Uint16Array
  58571. vertexData.indices.push(currentVertexDataIndex);
  58572. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  58573. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  58574. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  58575. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  58576. currentVertexDataIndex++;
  58577. }
  58578. }
  58579. // Return mesh
  58580. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  58581. vertexData.applyToMesh(decal);
  58582. decal.position = position.clone();
  58583. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  58584. return decal;
  58585. };
  58586. // Privates
  58587. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  58588. // extrusion geometry
  58589. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  58590. var tangents = path3D.getTangents();
  58591. var normals = path3D.getNormals();
  58592. var binormals = path3D.getBinormals();
  58593. var distances = path3D.getDistances();
  58594. var angle = 0;
  58595. var returnScale = function () { return scale !== null ? scale : 1; };
  58596. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  58597. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  58598. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  58599. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  58600. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  58601. for (var i = 0; i < curve.length; i++) {
  58602. var shapePath = new Array();
  58603. var angleStep = rotate(i, distances[i]);
  58604. var scaleRatio = scl(i, distances[i]);
  58605. for (var p = 0; p < shape.length; p++) {
  58606. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  58607. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  58608. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  58609. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  58610. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  58611. shapePath[p] = rotated;
  58612. }
  58613. shapePaths[index] = shapePath;
  58614. angle += angleStep;
  58615. index++;
  58616. }
  58617. // cap
  58618. var capPath = function (shapePath) {
  58619. var pointCap = Array();
  58620. var barycenter = BABYLON.Vector3.Zero();
  58621. var i;
  58622. for (i = 0; i < shapePath.length; i++) {
  58623. barycenter.addInPlace(shapePath[i]);
  58624. }
  58625. barycenter.scaleInPlace(1.0 / shapePath.length);
  58626. for (i = 0; i < shapePath.length; i++) {
  58627. pointCap.push(barycenter);
  58628. }
  58629. return pointCap;
  58630. };
  58631. switch (cap) {
  58632. case BABYLON.Mesh.NO_CAP:
  58633. break;
  58634. case BABYLON.Mesh.CAP_START:
  58635. shapePaths[0] = capPath(shapePaths[2]);
  58636. shapePaths[1] = shapePaths[2];
  58637. break;
  58638. case BABYLON.Mesh.CAP_END:
  58639. shapePaths[index] = shapePaths[index - 1];
  58640. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  58641. break;
  58642. case BABYLON.Mesh.CAP_ALL:
  58643. shapePaths[0] = capPath(shapePaths[2]);
  58644. shapePaths[1] = shapePaths[2];
  58645. shapePaths[index] = shapePaths[index - 1];
  58646. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  58647. break;
  58648. default:
  58649. break;
  58650. }
  58651. return shapePaths;
  58652. };
  58653. var path3D;
  58654. var pathArray;
  58655. if (instance) {
  58656. path3D = (instance.path3D).update(curve);
  58657. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  58658. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  58659. return instance;
  58660. }
  58661. // extruded shape creation
  58662. path3D = new BABYLON.Path3D(curve);
  58663. var newShapePaths = new Array();
  58664. cap = (cap < 0 || cap > 3) ? 0 : cap;
  58665. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  58666. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  58667. extrudedGeneric.pathArray = pathArray;
  58668. extrudedGeneric.path3D = path3D;
  58669. extrudedGeneric.cap = cap;
  58670. return extrudedGeneric;
  58671. };
  58672. return MeshBuilder;
  58673. }());
  58674. BABYLON.MeshBuilder = MeshBuilder;
  58675. })(BABYLON || (BABYLON = {}));
  58676. //# sourceMappingURL=babylon.meshBuilder.js.map
  58677. "use strict";
  58678. var BABYLON;
  58679. (function (BABYLON) {
  58680. /**
  58681. * Draco compression (https://google.github.io/draco/)
  58682. */
  58683. var DracoCompression = /** @class */ (function () {
  58684. /**
  58685. * Constructor
  58686. * @param numWorkers The number of workers for async operations
  58687. */
  58688. function DracoCompression(numWorkers) {
  58689. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  58690. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  58691. if (!workerBlobUrl || !Worker) {
  58692. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  58693. return;
  58694. }
  58695. var workers = new Array(numWorkers);
  58696. for (var i = 0; i < workers.length; i++) {
  58697. var worker = new Worker(workerBlobUrl);
  58698. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  58699. workers[i] = worker;
  58700. }
  58701. this._workerPool = new BABYLON.WorkerPool(workers);
  58702. }
  58703. /**
  58704. * Stop all async operations and release resources.
  58705. */
  58706. DracoCompression.prototype.dispose = function () {
  58707. this._workerPool.dispose();
  58708. delete this._workerPool;
  58709. };
  58710. /**
  58711. * Decode Draco compressed mesh data to vertex data.
  58712. * @param data The array buffer view for the Draco compression data
  58713. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  58714. * @returns A promise that resolves with the decoded vertex data
  58715. */
  58716. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  58717. var _this = this;
  58718. return new Promise(function (resolve, reject) {
  58719. _this._workerPool.push(function (worker, onComplete) {
  58720. var vertexData = new BABYLON.VertexData();
  58721. var onError = function (error) {
  58722. worker.removeEventListener("error", onError);
  58723. worker.removeEventListener("message", onMessage);
  58724. reject(error);
  58725. onComplete();
  58726. };
  58727. var onMessage = function (message) {
  58728. if (message.data === "done") {
  58729. worker.removeEventListener("error", onError);
  58730. worker.removeEventListener("message", onMessage);
  58731. resolve(vertexData);
  58732. onComplete();
  58733. }
  58734. else if (message.data.id === "indices") {
  58735. vertexData.indices = message.data.value;
  58736. }
  58737. else {
  58738. vertexData.set(message.data.value, message.data.id);
  58739. }
  58740. };
  58741. worker.addEventListener("error", onError);
  58742. worker.addEventListener("message", onMessage);
  58743. var dataCopy = new Uint8Array(data.byteLength);
  58744. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  58745. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  58746. });
  58747. });
  58748. };
  58749. /**
  58750. * The worker function that gets converted to a blob url to pass into a worker.
  58751. */
  58752. DracoCompression._Worker = function () {
  58753. // self is actually a DedicatedWorkerGlobalScope
  58754. var _self = self;
  58755. var decodeMesh = function (data, attributes) {
  58756. var dracoModule = new DracoDecoderModule();
  58757. var buffer = new dracoModule.DecoderBuffer();
  58758. buffer.Init(data, data.byteLength);
  58759. var decoder = new dracoModule.Decoder();
  58760. var geometry;
  58761. var status;
  58762. try {
  58763. var type = decoder.GetEncodedGeometryType(buffer);
  58764. switch (type) {
  58765. case dracoModule.TRIANGULAR_MESH:
  58766. geometry = new dracoModule.Mesh();
  58767. status = decoder.DecodeBufferToMesh(buffer, geometry);
  58768. break;
  58769. case dracoModule.POINT_CLOUD:
  58770. geometry = new dracoModule.PointCloud();
  58771. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  58772. break;
  58773. default:
  58774. throw new Error("Invalid geometry type " + type);
  58775. }
  58776. if (!status.ok() || !geometry.ptr) {
  58777. throw new Error(status.error_msg());
  58778. }
  58779. var numPoints = geometry.num_points();
  58780. if (type === dracoModule.TRIANGULAR_MESH) {
  58781. var numFaces = geometry.num_faces();
  58782. var faceIndices = new dracoModule.DracoInt32Array();
  58783. try {
  58784. var indices = new Uint32Array(numFaces * 3);
  58785. for (var i = 0; i < numFaces; i++) {
  58786. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  58787. var offset = i * 3;
  58788. indices[offset + 0] = faceIndices.GetValue(0);
  58789. indices[offset + 1] = faceIndices.GetValue(1);
  58790. indices[offset + 2] = faceIndices.GetValue(2);
  58791. }
  58792. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  58793. }
  58794. finally {
  58795. dracoModule.destroy(faceIndices);
  58796. }
  58797. }
  58798. for (var kind in attributes) {
  58799. var uniqueId = attributes[kind];
  58800. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  58801. var dracoData = new dracoModule.DracoFloat32Array();
  58802. try {
  58803. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  58804. var babylonData = new Float32Array(numPoints * attribute.num_components());
  58805. for (var i = 0; i < babylonData.length; i++) {
  58806. babylonData[i] = dracoData.GetValue(i);
  58807. }
  58808. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  58809. }
  58810. finally {
  58811. dracoModule.destroy(dracoData);
  58812. }
  58813. }
  58814. }
  58815. finally {
  58816. if (geometry) {
  58817. dracoModule.destroy(geometry);
  58818. }
  58819. dracoModule.destroy(decoder);
  58820. dracoModule.destroy(buffer);
  58821. }
  58822. _self.postMessage("done");
  58823. };
  58824. _self.onmessage = function (event) {
  58825. switch (event.data.id) {
  58826. case "initDecoder": {
  58827. importScripts(event.data.url);
  58828. break;
  58829. }
  58830. case "decodeMesh": {
  58831. decodeMesh(event.data.data, event.data.attributes);
  58832. break;
  58833. }
  58834. }
  58835. };
  58836. };
  58837. DracoCompression._GetDefaultDecoderUrl = function () {
  58838. if (!BABYLON.Tools.IsWindowObjectExist()) {
  58839. return null;
  58840. }
  58841. for (var i = 0; i < document.scripts.length; i++) {
  58842. if (document.scripts[i].type === "text/x-draco-decoder") {
  58843. return document.scripts[i].src;
  58844. }
  58845. }
  58846. return null;
  58847. };
  58848. /**
  58849. * Gets the url to the draco decoder if available.
  58850. */
  58851. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  58852. return DracoCompression;
  58853. }());
  58854. BABYLON.DracoCompression = DracoCompression;
  58855. })(BABYLON || (BABYLON = {}));
  58856. //# sourceMappingURL=babylon.dracoCompression.js.map
  58857. "use strict";
  58858. var BABYLON;
  58859. (function (BABYLON) {
  58860. var AudioEngine = /** @class */ (function () {
  58861. function AudioEngine() {
  58862. this._audioContext = null;
  58863. this._audioContextInitialized = false;
  58864. this.canUseWebAudio = false;
  58865. this.WarnedWebAudioUnsupported = false;
  58866. this.unlocked = false;
  58867. this.isMP3supported = false;
  58868. this.isOGGsupported = false;
  58869. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  58870. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  58871. this.canUseWebAudio = true;
  58872. }
  58873. var audioElem = document.createElement('audio');
  58874. try {
  58875. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  58876. this.isMP3supported = true;
  58877. }
  58878. }
  58879. catch (e) {
  58880. // protect error during capability check.
  58881. }
  58882. try {
  58883. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  58884. this.isOGGsupported = true;
  58885. }
  58886. }
  58887. catch (e) {
  58888. // protect error during capability check.
  58889. }
  58890. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  58891. this._unlockiOSaudio();
  58892. }
  58893. else {
  58894. this.unlocked = true;
  58895. }
  58896. }
  58897. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  58898. get: function () {
  58899. if (!this._audioContextInitialized) {
  58900. this._initializeAudioContext();
  58901. }
  58902. return this._audioContext;
  58903. },
  58904. enumerable: true,
  58905. configurable: true
  58906. });
  58907. AudioEngine.prototype._unlockiOSaudio = function () {
  58908. var _this = this;
  58909. var unlockaudio = function () {
  58910. if (!_this.audioContext) {
  58911. return;
  58912. }
  58913. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  58914. var source = _this.audioContext.createBufferSource();
  58915. source.buffer = buffer;
  58916. source.connect(_this.audioContext.destination);
  58917. source.start(0);
  58918. setTimeout(function () {
  58919. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  58920. _this.unlocked = true;
  58921. window.removeEventListener('touchend', unlockaudio, false);
  58922. if (_this.onAudioUnlocked) {
  58923. _this.onAudioUnlocked();
  58924. }
  58925. }
  58926. }, 0);
  58927. };
  58928. window.addEventListener('touchend', unlockaudio, false);
  58929. };
  58930. AudioEngine.prototype._initializeAudioContext = function () {
  58931. try {
  58932. if (this.canUseWebAudio) {
  58933. this._audioContext = new AudioContext();
  58934. // create a global volume gain node
  58935. this.masterGain = this._audioContext.createGain();
  58936. this.masterGain.gain.value = 1;
  58937. this.masterGain.connect(this._audioContext.destination);
  58938. this._audioContextInitialized = true;
  58939. }
  58940. }
  58941. catch (e) {
  58942. this.canUseWebAudio = false;
  58943. BABYLON.Tools.Error("Web Audio: " + e.message);
  58944. }
  58945. };
  58946. AudioEngine.prototype.dispose = function () {
  58947. if (this.canUseWebAudio && this._audioContextInitialized) {
  58948. if (this._connectedAnalyser && this._audioContext) {
  58949. this._connectedAnalyser.stopDebugCanvas();
  58950. this._connectedAnalyser.dispose();
  58951. this.masterGain.disconnect();
  58952. this.masterGain.connect(this._audioContext.destination);
  58953. this._connectedAnalyser = null;
  58954. }
  58955. this.masterGain.gain.value = 1;
  58956. }
  58957. this.WarnedWebAudioUnsupported = false;
  58958. };
  58959. AudioEngine.prototype.getGlobalVolume = function () {
  58960. if (this.canUseWebAudio && this._audioContextInitialized) {
  58961. return this.masterGain.gain.value;
  58962. }
  58963. else {
  58964. return -1;
  58965. }
  58966. };
  58967. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  58968. if (this.canUseWebAudio && this._audioContextInitialized) {
  58969. this.masterGain.gain.value = newVolume;
  58970. }
  58971. };
  58972. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  58973. if (this._connectedAnalyser) {
  58974. this._connectedAnalyser.stopDebugCanvas();
  58975. }
  58976. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  58977. this._connectedAnalyser = analyser;
  58978. this.masterGain.disconnect();
  58979. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  58980. }
  58981. };
  58982. return AudioEngine;
  58983. }());
  58984. BABYLON.AudioEngine = AudioEngine;
  58985. })(BABYLON || (BABYLON = {}));
  58986. //# sourceMappingURL=babylon.audioEngine.js.map
  58987. "use strict";
  58988. var BABYLON;
  58989. (function (BABYLON) {
  58990. var Sound = /** @class */ (function () {
  58991. /**
  58992. * Create a sound and attach it to a scene
  58993. * @param name Name of your sound
  58994. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  58995. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  58996. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  58997. */
  58998. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  58999. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  59000. var _this = this;
  59001. this.autoplay = false;
  59002. this.loop = false;
  59003. this.useCustomAttenuation = false;
  59004. this.spatialSound = false;
  59005. this.refDistance = 1;
  59006. this.rolloffFactor = 1;
  59007. this.maxDistance = 100;
  59008. this.distanceModel = "linear";
  59009. this._panningModel = "equalpower";
  59010. this._playbackRate = 1;
  59011. this._streaming = false;
  59012. this._startTime = 0;
  59013. this._startOffset = 0;
  59014. this._position = BABYLON.Vector3.Zero();
  59015. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  59016. this._volume = 1;
  59017. this._isReadyToPlay = false;
  59018. this.isPlaying = false;
  59019. this.isPaused = false;
  59020. this._isDirectional = false;
  59021. // Used if you'd like to create a directional sound.
  59022. // If not set, the sound will be omnidirectional
  59023. this._coneInnerAngle = 360;
  59024. this._coneOuterAngle = 360;
  59025. this._coneOuterGain = 0;
  59026. this._isOutputConnected = false;
  59027. this._urlType = "Unknown";
  59028. this.name = name;
  59029. this._scene = scene;
  59030. this._readyToPlayCallback = readyToPlayCallback;
  59031. // Default custom attenuation function is a linear attenuation
  59032. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  59033. if (currentDistance < maxDistance) {
  59034. return currentVolume * (1 - currentDistance / maxDistance);
  59035. }
  59036. else {
  59037. return 0;
  59038. }
  59039. };
  59040. if (options) {
  59041. this.autoplay = options.autoplay || false;
  59042. this.loop = options.loop || false;
  59043. // if volume === 0, we need another way to check this option
  59044. if (options.volume !== undefined) {
  59045. this._volume = options.volume;
  59046. }
  59047. this.spatialSound = options.spatialSound || false;
  59048. this.maxDistance = options.maxDistance || 100;
  59049. this.useCustomAttenuation = options.useCustomAttenuation || false;
  59050. this.rolloffFactor = options.rolloffFactor || 1;
  59051. this.refDistance = options.refDistance || 1;
  59052. this.distanceModel = options.distanceModel || "linear";
  59053. this._playbackRate = options.playbackRate || 1;
  59054. this._streaming = options.streaming || false;
  59055. }
  59056. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  59057. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  59058. this._soundGain.gain.value = this._volume;
  59059. this._inputAudioNode = this._soundGain;
  59060. this._ouputAudioNode = this._soundGain;
  59061. if (this.spatialSound) {
  59062. this._createSpatialParameters();
  59063. }
  59064. this._scene.mainSoundTrack.AddSound(this);
  59065. var validParameter = true;
  59066. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  59067. if (urlOrArrayBuffer) {
  59068. try {
  59069. if (typeof (urlOrArrayBuffer) === "string")
  59070. this._urlType = "String";
  59071. if (Array.isArray(urlOrArrayBuffer))
  59072. this._urlType = "Array";
  59073. if (urlOrArrayBuffer instanceof ArrayBuffer)
  59074. this._urlType = "ArrayBuffer";
  59075. var urls = [];
  59076. var codecSupportedFound = false;
  59077. switch (this._urlType) {
  59078. case "ArrayBuffer":
  59079. if (urlOrArrayBuffer.byteLength > 0) {
  59080. codecSupportedFound = true;
  59081. this._soundLoaded(urlOrArrayBuffer);
  59082. }
  59083. break;
  59084. case "String":
  59085. urls.push(urlOrArrayBuffer);
  59086. case "Array":
  59087. if (urls.length === 0)
  59088. urls = urlOrArrayBuffer;
  59089. // If we found a supported format, we load it immediately and stop the loop
  59090. for (var i = 0; i < urls.length; i++) {
  59091. var url = urls[i];
  59092. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  59093. codecSupportedFound = true;
  59094. }
  59095. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  59096. codecSupportedFound = true;
  59097. }
  59098. if (url.indexOf(".wav", url.length - 4) !== -1) {
  59099. codecSupportedFound = true;
  59100. }
  59101. if (url.indexOf("blob:") !== -1) {
  59102. codecSupportedFound = true;
  59103. }
  59104. if (codecSupportedFound) {
  59105. // Loading sound using XHR2
  59106. if (!this._streaming) {
  59107. this._scene._loadFile(url, function (data) {
  59108. _this._soundLoaded(data);
  59109. }, undefined, true, true, function (exception) {
  59110. if (exception) {
  59111. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  59112. }
  59113. BABYLON.Tools.Error("Sound creation aborted.");
  59114. _this._scene.mainSoundTrack.RemoveSound(_this);
  59115. });
  59116. }
  59117. else {
  59118. this._htmlAudioElement = new Audio(url);
  59119. this._htmlAudioElement.controls = false;
  59120. this._htmlAudioElement.loop = this.loop;
  59121. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  59122. this._htmlAudioElement.preload = "auto";
  59123. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  59124. _this._isReadyToPlay = true;
  59125. if (_this.autoplay) {
  59126. _this.play();
  59127. }
  59128. if (_this._readyToPlayCallback) {
  59129. _this._readyToPlayCallback();
  59130. }
  59131. });
  59132. document.body.appendChild(this._htmlAudioElement);
  59133. }
  59134. break;
  59135. }
  59136. }
  59137. break;
  59138. default:
  59139. validParameter = false;
  59140. break;
  59141. }
  59142. if (!validParameter) {
  59143. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  59144. }
  59145. else {
  59146. if (!codecSupportedFound) {
  59147. this._isReadyToPlay = true;
  59148. // Simulating a ready to play event to avoid breaking code path
  59149. if (this._readyToPlayCallback) {
  59150. window.setTimeout(function () {
  59151. if (_this._readyToPlayCallback) {
  59152. _this._readyToPlayCallback();
  59153. }
  59154. }, 1000);
  59155. }
  59156. }
  59157. }
  59158. }
  59159. catch (ex) {
  59160. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  59161. this._scene.mainSoundTrack.RemoveSound(this);
  59162. }
  59163. }
  59164. }
  59165. else {
  59166. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  59167. this._scene.mainSoundTrack.AddSound(this);
  59168. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  59169. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  59170. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  59171. }
  59172. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  59173. if (this._readyToPlayCallback) {
  59174. window.setTimeout(function () {
  59175. if (_this._readyToPlayCallback) {
  59176. _this._readyToPlayCallback();
  59177. }
  59178. }, 1000);
  59179. }
  59180. }
  59181. }
  59182. Sound.prototype.dispose = function () {
  59183. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59184. if (this.isPlaying) {
  59185. this.stop();
  59186. }
  59187. this._isReadyToPlay = false;
  59188. if (this.soundTrackId === -1) {
  59189. this._scene.mainSoundTrack.RemoveSound(this);
  59190. }
  59191. else {
  59192. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  59193. }
  59194. if (this._soundGain) {
  59195. this._soundGain.disconnect();
  59196. this._soundGain = null;
  59197. }
  59198. if (this._soundPanner) {
  59199. this._soundPanner.disconnect();
  59200. this._soundPanner = null;
  59201. }
  59202. if (this._soundSource) {
  59203. this._soundSource.disconnect();
  59204. this._soundSource = null;
  59205. }
  59206. this._audioBuffer = null;
  59207. if (this._htmlAudioElement) {
  59208. this._htmlAudioElement.pause();
  59209. this._htmlAudioElement.src = "";
  59210. document.body.removeChild(this._htmlAudioElement);
  59211. }
  59212. if (this._connectedMesh && this._registerFunc) {
  59213. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  59214. this._connectedMesh = null;
  59215. }
  59216. }
  59217. };
  59218. Sound.prototype.isReady = function () {
  59219. return this._isReadyToPlay;
  59220. };
  59221. Sound.prototype._soundLoaded = function (audioData) {
  59222. var _this = this;
  59223. if (!BABYLON.Engine.audioEngine.audioContext) {
  59224. return;
  59225. }
  59226. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  59227. _this._audioBuffer = buffer;
  59228. _this._isReadyToPlay = true;
  59229. if (_this.autoplay) {
  59230. _this.play();
  59231. }
  59232. if (_this._readyToPlayCallback) {
  59233. _this._readyToPlayCallback();
  59234. }
  59235. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  59236. };
  59237. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  59238. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59239. this._audioBuffer = audioBuffer;
  59240. this._isReadyToPlay = true;
  59241. }
  59242. };
  59243. Sound.prototype.updateOptions = function (options) {
  59244. if (options) {
  59245. this.loop = options.loop || this.loop;
  59246. this.maxDistance = options.maxDistance || this.maxDistance;
  59247. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  59248. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  59249. this.refDistance = options.refDistance || this.refDistance;
  59250. this.distanceModel = options.distanceModel || this.distanceModel;
  59251. this._playbackRate = options.playbackRate || this._playbackRate;
  59252. this._updateSpatialParameters();
  59253. if (this.isPlaying) {
  59254. if (this._streaming) {
  59255. this._htmlAudioElement.playbackRate = this._playbackRate;
  59256. }
  59257. else {
  59258. if (this._soundSource) {
  59259. this._soundSource.playbackRate.value = this._playbackRate;
  59260. }
  59261. }
  59262. }
  59263. }
  59264. };
  59265. Sound.prototype._createSpatialParameters = function () {
  59266. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  59267. if (this._scene.headphone) {
  59268. this._panningModel = "HRTF";
  59269. }
  59270. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  59271. this._updateSpatialParameters();
  59272. this._soundPanner.connect(this._ouputAudioNode);
  59273. this._inputAudioNode = this._soundPanner;
  59274. }
  59275. };
  59276. Sound.prototype._updateSpatialParameters = function () {
  59277. if (this.spatialSound && this._soundPanner) {
  59278. if (this.useCustomAttenuation) {
  59279. // Tricks to disable in a way embedded Web Audio attenuation
  59280. this._soundPanner.distanceModel = "linear";
  59281. this._soundPanner.maxDistance = Number.MAX_VALUE;
  59282. this._soundPanner.refDistance = 1;
  59283. this._soundPanner.rolloffFactor = 1;
  59284. this._soundPanner.panningModel = this._panningModel;
  59285. }
  59286. else {
  59287. this._soundPanner.distanceModel = this.distanceModel;
  59288. this._soundPanner.maxDistance = this.maxDistance;
  59289. this._soundPanner.refDistance = this.refDistance;
  59290. this._soundPanner.rolloffFactor = this.rolloffFactor;
  59291. this._soundPanner.panningModel = this._panningModel;
  59292. }
  59293. }
  59294. };
  59295. Sound.prototype.switchPanningModelToHRTF = function () {
  59296. this._panningModel = "HRTF";
  59297. this._switchPanningModel();
  59298. };
  59299. Sound.prototype.switchPanningModelToEqualPower = function () {
  59300. this._panningModel = "equalpower";
  59301. this._switchPanningModel();
  59302. };
  59303. Sound.prototype._switchPanningModel = function () {
  59304. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  59305. this._soundPanner.panningModel = this._panningModel;
  59306. }
  59307. };
  59308. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  59309. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59310. if (this._isOutputConnected) {
  59311. this._ouputAudioNode.disconnect();
  59312. }
  59313. this._ouputAudioNode.connect(soundTrackAudioNode);
  59314. this._isOutputConnected = true;
  59315. }
  59316. };
  59317. /**
  59318. * Transform this sound into a directional source
  59319. * @param coneInnerAngle Size of the inner cone in degree
  59320. * @param coneOuterAngle Size of the outer cone in degree
  59321. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  59322. */
  59323. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  59324. if (coneOuterAngle < coneInnerAngle) {
  59325. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  59326. return;
  59327. }
  59328. this._coneInnerAngle = coneInnerAngle;
  59329. this._coneOuterAngle = coneOuterAngle;
  59330. this._coneOuterGain = coneOuterGain;
  59331. this._isDirectional = true;
  59332. if (this.isPlaying && this.loop) {
  59333. this.stop();
  59334. this.play();
  59335. }
  59336. };
  59337. Sound.prototype.setPosition = function (newPosition) {
  59338. this._position = newPosition;
  59339. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  59340. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  59341. }
  59342. };
  59343. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  59344. this._localDirection = newLocalDirection;
  59345. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  59346. this._updateDirection();
  59347. }
  59348. };
  59349. Sound.prototype._updateDirection = function () {
  59350. if (!this._connectedMesh || !this._soundPanner) {
  59351. return;
  59352. }
  59353. var mat = this._connectedMesh.getWorldMatrix();
  59354. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  59355. direction.normalize();
  59356. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  59357. };
  59358. Sound.prototype.updateDistanceFromListener = function () {
  59359. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  59360. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  59361. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  59362. }
  59363. };
  59364. Sound.prototype.setAttenuationFunction = function (callback) {
  59365. this._customAttenuationFunction = callback;
  59366. };
  59367. /**
  59368. * Play the sound
  59369. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  59370. * @param offset (optional) Start the sound setting it at a specific time
  59371. */
  59372. Sound.prototype.play = function (time, offset) {
  59373. var _this = this;
  59374. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  59375. try {
  59376. if (this._startOffset < 0) {
  59377. time = -this._startOffset;
  59378. this._startOffset = 0;
  59379. }
  59380. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  59381. if (!this._soundSource || !this._streamingSource) {
  59382. if (this.spatialSound && this._soundPanner) {
  59383. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  59384. if (this._isDirectional) {
  59385. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  59386. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  59387. this._soundPanner.coneOuterGain = this._coneOuterGain;
  59388. if (this._connectedMesh) {
  59389. this._updateDirection();
  59390. }
  59391. else {
  59392. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  59393. }
  59394. }
  59395. }
  59396. }
  59397. if (this._streaming) {
  59398. if (!this._streamingSource) {
  59399. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  59400. this._htmlAudioElement.onended = function () { _this._onended(); };
  59401. this._htmlAudioElement.playbackRate = this._playbackRate;
  59402. }
  59403. this._streamingSource.disconnect();
  59404. this._streamingSource.connect(this._inputAudioNode);
  59405. this._htmlAudioElement.play();
  59406. }
  59407. else {
  59408. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  59409. this._soundSource.buffer = this._audioBuffer;
  59410. this._soundSource.connect(this._inputAudioNode);
  59411. this._soundSource.loop = this.loop;
  59412. this._soundSource.playbackRate.value = this._playbackRate;
  59413. this._soundSource.onended = function () { _this._onended(); };
  59414. if (this._soundSource.buffer) {
  59415. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  59416. }
  59417. }
  59418. this._startTime = startTime;
  59419. this.isPlaying = true;
  59420. this.isPaused = false;
  59421. }
  59422. catch (ex) {
  59423. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  59424. }
  59425. }
  59426. };
  59427. Sound.prototype._onended = function () {
  59428. this.isPlaying = false;
  59429. if (this.onended) {
  59430. this.onended();
  59431. }
  59432. };
  59433. /**
  59434. * Stop the sound
  59435. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  59436. */
  59437. Sound.prototype.stop = function (time) {
  59438. if (this.isPlaying) {
  59439. if (this._streaming) {
  59440. this._htmlAudioElement.pause();
  59441. // Test needed for Firefox or it will generate an Invalid State Error
  59442. if (this._htmlAudioElement.currentTime > 0) {
  59443. this._htmlAudioElement.currentTime = 0;
  59444. }
  59445. }
  59446. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  59447. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  59448. this._soundSource.stop(stopTime);
  59449. this._soundSource.onended = function () { };
  59450. if (!this.isPaused) {
  59451. this._startOffset = 0;
  59452. }
  59453. }
  59454. this.isPlaying = false;
  59455. }
  59456. };
  59457. Sound.prototype.pause = function () {
  59458. if (this.isPlaying) {
  59459. this.isPaused = true;
  59460. if (this._streaming) {
  59461. this._htmlAudioElement.pause();
  59462. }
  59463. else if (BABYLON.Engine.audioEngine.audioContext) {
  59464. this.stop(0);
  59465. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  59466. }
  59467. }
  59468. };
  59469. Sound.prototype.setVolume = function (newVolume, time) {
  59470. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  59471. if (time && BABYLON.Engine.audioEngine.audioContext) {
  59472. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  59473. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  59474. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  59475. }
  59476. else {
  59477. this._soundGain.gain.value = newVolume;
  59478. }
  59479. }
  59480. this._volume = newVolume;
  59481. };
  59482. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  59483. this._playbackRate = newPlaybackRate;
  59484. if (this.isPlaying) {
  59485. if (this._streaming) {
  59486. this._htmlAudioElement.playbackRate = this._playbackRate;
  59487. }
  59488. else if (this._soundSource) {
  59489. this._soundSource.playbackRate.value = this._playbackRate;
  59490. }
  59491. }
  59492. };
  59493. Sound.prototype.getVolume = function () {
  59494. return this._volume;
  59495. };
  59496. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  59497. var _this = this;
  59498. if (this._connectedMesh && this._registerFunc) {
  59499. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  59500. this._registerFunc = null;
  59501. }
  59502. this._connectedMesh = meshToConnectTo;
  59503. if (!this.spatialSound) {
  59504. this.spatialSound = true;
  59505. this._createSpatialParameters();
  59506. if (this.isPlaying && this.loop) {
  59507. this.stop();
  59508. this.play();
  59509. }
  59510. }
  59511. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  59512. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  59513. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  59514. };
  59515. Sound.prototype.detachFromMesh = function () {
  59516. if (this._connectedMesh && this._registerFunc) {
  59517. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  59518. this._registerFunc = null;
  59519. this._connectedMesh = null;
  59520. }
  59521. };
  59522. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  59523. if (!node.getBoundingInfo) {
  59524. return;
  59525. }
  59526. var mesh = node;
  59527. var boundingInfo = mesh.getBoundingInfo();
  59528. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  59529. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  59530. this._updateDirection();
  59531. }
  59532. };
  59533. Sound.prototype.clone = function () {
  59534. var _this = this;
  59535. if (!this._streaming) {
  59536. var setBufferAndRun = function () {
  59537. if (_this._isReadyToPlay) {
  59538. clonedSound._audioBuffer = _this.getAudioBuffer();
  59539. clonedSound._isReadyToPlay = true;
  59540. if (clonedSound.autoplay) {
  59541. clonedSound.play();
  59542. }
  59543. }
  59544. else {
  59545. window.setTimeout(setBufferAndRun, 300);
  59546. }
  59547. };
  59548. var currentOptions = {
  59549. autoplay: this.autoplay, loop: this.loop,
  59550. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  59551. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  59552. refDistance: this.refDistance, distanceModel: this.distanceModel
  59553. };
  59554. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  59555. if (this.useCustomAttenuation) {
  59556. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  59557. }
  59558. clonedSound.setPosition(this._position);
  59559. clonedSound.setPlaybackRate(this._playbackRate);
  59560. setBufferAndRun();
  59561. return clonedSound;
  59562. }
  59563. else {
  59564. return null;
  59565. }
  59566. };
  59567. Sound.prototype.getAudioBuffer = function () {
  59568. return this._audioBuffer;
  59569. };
  59570. Sound.prototype.serialize = function () {
  59571. var serializationObject = {
  59572. name: this.name,
  59573. url: this.name,
  59574. autoplay: this.autoplay,
  59575. loop: this.loop,
  59576. volume: this._volume,
  59577. spatialSound: this.spatialSound,
  59578. maxDistance: this.maxDistance,
  59579. rolloffFactor: this.rolloffFactor,
  59580. refDistance: this.refDistance,
  59581. distanceModel: this.distanceModel,
  59582. playbackRate: this._playbackRate,
  59583. panningModel: this._panningModel,
  59584. soundTrackId: this.soundTrackId
  59585. };
  59586. if (this.spatialSound) {
  59587. if (this._connectedMesh)
  59588. serializationObject.connectedMeshId = this._connectedMesh.id;
  59589. serializationObject.position = this._position.asArray();
  59590. serializationObject.refDistance = this.refDistance;
  59591. serializationObject.distanceModel = this.distanceModel;
  59592. serializationObject.isDirectional = this._isDirectional;
  59593. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  59594. serializationObject.coneInnerAngle = this._coneInnerAngle;
  59595. serializationObject.coneOuterAngle = this._coneOuterAngle;
  59596. serializationObject.coneOuterGain = this._coneOuterGain;
  59597. }
  59598. return serializationObject;
  59599. };
  59600. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  59601. var soundName = parsedSound.name;
  59602. var soundUrl;
  59603. if (parsedSound.url) {
  59604. soundUrl = rootUrl + parsedSound.url;
  59605. }
  59606. else {
  59607. soundUrl = rootUrl + soundName;
  59608. }
  59609. var options = {
  59610. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  59611. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  59612. rolloffFactor: parsedSound.rolloffFactor,
  59613. refDistance: parsedSound.refDistance,
  59614. distanceModel: parsedSound.distanceModel,
  59615. playbackRate: parsedSound.playbackRate
  59616. };
  59617. var newSound;
  59618. if (!sourceSound) {
  59619. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  59620. scene._addPendingData(newSound);
  59621. }
  59622. else {
  59623. var setBufferAndRun = function () {
  59624. if (sourceSound._isReadyToPlay) {
  59625. newSound._audioBuffer = sourceSound.getAudioBuffer();
  59626. newSound._isReadyToPlay = true;
  59627. if (newSound.autoplay) {
  59628. newSound.play();
  59629. }
  59630. }
  59631. else {
  59632. window.setTimeout(setBufferAndRun, 300);
  59633. }
  59634. };
  59635. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  59636. setBufferAndRun();
  59637. }
  59638. if (parsedSound.position) {
  59639. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  59640. newSound.setPosition(soundPosition);
  59641. }
  59642. if (parsedSound.isDirectional) {
  59643. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  59644. if (parsedSound.localDirectionToMesh) {
  59645. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  59646. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  59647. }
  59648. }
  59649. if (parsedSound.connectedMeshId) {
  59650. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  59651. if (connectedMesh) {
  59652. newSound.attachToMesh(connectedMesh);
  59653. }
  59654. }
  59655. return newSound;
  59656. };
  59657. return Sound;
  59658. }());
  59659. BABYLON.Sound = Sound;
  59660. })(BABYLON || (BABYLON = {}));
  59661. //# sourceMappingURL=babylon.sound.js.map
  59662. "use strict";
  59663. var BABYLON;
  59664. (function (BABYLON) {
  59665. var SoundTrack = /** @class */ (function () {
  59666. function SoundTrack(scene, options) {
  59667. this.id = -1;
  59668. this._isMainTrack = false;
  59669. this._isInitialized = false;
  59670. this._scene = scene;
  59671. this.soundCollection = new Array();
  59672. this._options = options;
  59673. if (!this._isMainTrack) {
  59674. this._scene.soundTracks.push(this);
  59675. this.id = this._scene.soundTracks.length - 1;
  59676. }
  59677. }
  59678. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  59679. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  59680. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  59681. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  59682. if (this._options) {
  59683. if (this._options.volume) {
  59684. this._outputAudioNode.gain.value = this._options.volume;
  59685. }
  59686. if (this._options.mainTrack) {
  59687. this._isMainTrack = this._options.mainTrack;
  59688. }
  59689. }
  59690. this._isInitialized = true;
  59691. }
  59692. };
  59693. SoundTrack.prototype.dispose = function () {
  59694. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  59695. if (this._connectedAnalyser) {
  59696. this._connectedAnalyser.stopDebugCanvas();
  59697. }
  59698. while (this.soundCollection.length) {
  59699. this.soundCollection[0].dispose();
  59700. }
  59701. if (this._outputAudioNode) {
  59702. this._outputAudioNode.disconnect();
  59703. }
  59704. this._outputAudioNode = null;
  59705. }
  59706. };
  59707. SoundTrack.prototype.AddSound = function (sound) {
  59708. if (!this._isInitialized) {
  59709. this._initializeSoundTrackAudioGraph();
  59710. }
  59711. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  59712. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  59713. }
  59714. if (sound.soundTrackId) {
  59715. if (sound.soundTrackId === -1) {
  59716. this._scene.mainSoundTrack.RemoveSound(sound);
  59717. }
  59718. else {
  59719. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  59720. }
  59721. }
  59722. this.soundCollection.push(sound);
  59723. sound.soundTrackId = this.id;
  59724. };
  59725. SoundTrack.prototype.RemoveSound = function (sound) {
  59726. var index = this.soundCollection.indexOf(sound);
  59727. if (index !== -1) {
  59728. this.soundCollection.splice(index, 1);
  59729. }
  59730. };
  59731. SoundTrack.prototype.setVolume = function (newVolume) {
  59732. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  59733. this._outputAudioNode.gain.value = newVolume;
  59734. }
  59735. };
  59736. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  59737. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59738. for (var i = 0; i < this.soundCollection.length; i++) {
  59739. this.soundCollection[i].switchPanningModelToHRTF();
  59740. }
  59741. }
  59742. };
  59743. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  59744. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59745. for (var i = 0; i < this.soundCollection.length; i++) {
  59746. this.soundCollection[i].switchPanningModelToEqualPower();
  59747. }
  59748. }
  59749. };
  59750. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  59751. if (this._connectedAnalyser) {
  59752. this._connectedAnalyser.stopDebugCanvas();
  59753. }
  59754. this._connectedAnalyser = analyser;
  59755. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  59756. this._outputAudioNode.disconnect();
  59757. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  59758. }
  59759. };
  59760. return SoundTrack;
  59761. }());
  59762. BABYLON.SoundTrack = SoundTrack;
  59763. })(BABYLON || (BABYLON = {}));
  59764. //# sourceMappingURL=babylon.soundtrack.js.map
  59765. "use strict";
  59766. var BABYLON;
  59767. (function (BABYLON) {
  59768. var Analyser = /** @class */ (function () {
  59769. function Analyser(scene) {
  59770. this.SMOOTHING = 0.75;
  59771. this.FFT_SIZE = 512;
  59772. this.BARGRAPHAMPLITUDE = 256;
  59773. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  59774. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  59775. this._scene = scene;
  59776. this._audioEngine = BABYLON.Engine.audioEngine;
  59777. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  59778. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  59779. this._webAudioAnalyser.minDecibels = -140;
  59780. this._webAudioAnalyser.maxDecibels = 0;
  59781. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  59782. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  59783. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  59784. }
  59785. }
  59786. Analyser.prototype.getFrequencyBinCount = function () {
  59787. if (this._audioEngine.canUseWebAudio) {
  59788. return this._webAudioAnalyser.frequencyBinCount;
  59789. }
  59790. else {
  59791. return 0;
  59792. }
  59793. };
  59794. Analyser.prototype.getByteFrequencyData = function () {
  59795. if (this._audioEngine.canUseWebAudio) {
  59796. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  59797. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  59798. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  59799. }
  59800. return this._byteFreqs;
  59801. };
  59802. Analyser.prototype.getByteTimeDomainData = function () {
  59803. if (this._audioEngine.canUseWebAudio) {
  59804. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  59805. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  59806. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  59807. }
  59808. return this._byteTime;
  59809. };
  59810. Analyser.prototype.getFloatFrequencyData = function () {
  59811. if (this._audioEngine.canUseWebAudio) {
  59812. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  59813. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  59814. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  59815. }
  59816. return this._floatFreqs;
  59817. };
  59818. Analyser.prototype.drawDebugCanvas = function () {
  59819. var _this = this;
  59820. if (this._audioEngine.canUseWebAudio) {
  59821. if (!this._debugCanvas) {
  59822. this._debugCanvas = document.createElement("canvas");
  59823. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  59824. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  59825. this._debugCanvas.style.position = "absolute";
  59826. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  59827. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  59828. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  59829. document.body.appendChild(this._debugCanvas);
  59830. this._registerFunc = function () {
  59831. _this.drawDebugCanvas();
  59832. };
  59833. this._scene.registerBeforeRender(this._registerFunc);
  59834. }
  59835. if (this._registerFunc && this._debugCanvasContext) {
  59836. var workingArray = this.getByteFrequencyData();
  59837. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  59838. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  59839. // Draw the frequency domain chart.
  59840. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  59841. var value = workingArray[i];
  59842. var percent = value / this.BARGRAPHAMPLITUDE;
  59843. var height = this.DEBUGCANVASSIZE.height * percent;
  59844. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  59845. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  59846. var hue = i / this.getFrequencyBinCount() * 360;
  59847. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  59848. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  59849. }
  59850. }
  59851. }
  59852. };
  59853. Analyser.prototype.stopDebugCanvas = function () {
  59854. if (this._debugCanvas) {
  59855. if (this._registerFunc) {
  59856. this._scene.unregisterBeforeRender(this._registerFunc);
  59857. this._registerFunc = null;
  59858. }
  59859. document.body.removeChild(this._debugCanvas);
  59860. this._debugCanvas = null;
  59861. this._debugCanvasContext = null;
  59862. }
  59863. };
  59864. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  59865. if (this._audioEngine.canUseWebAudio) {
  59866. inputAudioNode.connect(this._webAudioAnalyser);
  59867. this._webAudioAnalyser.connect(outputAudioNode);
  59868. }
  59869. };
  59870. Analyser.prototype.dispose = function () {
  59871. if (this._audioEngine.canUseWebAudio) {
  59872. this._webAudioAnalyser.disconnect();
  59873. }
  59874. };
  59875. return Analyser;
  59876. }());
  59877. BABYLON.Analyser = Analyser;
  59878. })(BABYLON || (BABYLON = {}));
  59879. //# sourceMappingURL=babylon.analyser.js.map
  59880. "use strict";
  59881. var BABYLON;
  59882. (function (BABYLON) {
  59883. var CubeTexture = /** @class */ (function (_super) {
  59884. __extends(CubeTexture, _super);
  59885. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  59886. if (extensions === void 0) { extensions = null; }
  59887. if (noMipmap === void 0) { noMipmap = false; }
  59888. if (files === void 0) { files = null; }
  59889. if (onLoad === void 0) { onLoad = null; }
  59890. if (onError === void 0) { onError = null; }
  59891. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59892. if (prefiltered === void 0) { prefiltered = false; }
  59893. if (forcedExtension === void 0) { forcedExtension = null; }
  59894. var _this = _super.call(this, scene) || this;
  59895. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59896. /**
  59897. * Gets or sets the center of the bounding box associated with the cube texture
  59898. * It must define where the camera used to render the texture was set
  59899. */
  59900. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59901. _this.name = rootUrl;
  59902. _this.url = rootUrl;
  59903. _this._noMipmap = noMipmap;
  59904. _this.hasAlpha = false;
  59905. _this._format = format;
  59906. _this._prefiltered = prefiltered;
  59907. _this.isCube = true;
  59908. _this._textureMatrix = BABYLON.Matrix.Identity();
  59909. if (prefiltered) {
  59910. _this.gammaSpace = false;
  59911. }
  59912. if (!rootUrl && !files) {
  59913. return _this;
  59914. }
  59915. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  59916. var lastDot = rootUrl.lastIndexOf(".");
  59917. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  59918. var isDDS = (extension === ".dds");
  59919. if (!files) {
  59920. if (!isDDS && !extensions) {
  59921. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  59922. }
  59923. files = [];
  59924. if (extensions) {
  59925. for (var index = 0; index < extensions.length; index++) {
  59926. files.push(rootUrl + extensions[index]);
  59927. }
  59928. }
  59929. }
  59930. _this._files = files;
  59931. if (!_this._texture) {
  59932. if (!scene.useDelayedTextureLoading) {
  59933. if (prefiltered) {
  59934. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  59935. }
  59936. else {
  59937. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  59938. }
  59939. }
  59940. else {
  59941. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59942. }
  59943. }
  59944. else if (onLoad) {
  59945. if (_this._texture.isReady) {
  59946. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  59947. }
  59948. else {
  59949. _this._texture.onLoadedObservable.add(onLoad);
  59950. }
  59951. }
  59952. return _this;
  59953. }
  59954. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  59955. get: function () {
  59956. return this._boundingBoxSize;
  59957. },
  59958. /**
  59959. * Gets or sets the size of the bounding box associated with the cube texture
  59960. * When defined, the cubemap will switch to local mode
  59961. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59962. * @example https://www.babylonjs-playground.com/#RNASML
  59963. */
  59964. set: function (value) {
  59965. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59966. return;
  59967. }
  59968. this._boundingBoxSize = value;
  59969. var scene = this.getScene();
  59970. if (scene) {
  59971. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59972. }
  59973. },
  59974. enumerable: true,
  59975. configurable: true
  59976. });
  59977. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  59978. var rootUrlKey = "";
  59979. files.forEach(function (url) { return rootUrlKey += url; });
  59980. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  59981. };
  59982. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  59983. if (forcedExtension === void 0) { forcedExtension = null; }
  59984. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  59985. };
  59986. // Methods
  59987. CubeTexture.prototype.delayLoad = function () {
  59988. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59989. return;
  59990. }
  59991. var scene = this.getScene();
  59992. if (!scene) {
  59993. return;
  59994. }
  59995. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59996. this._texture = this._getFromCache(this.url, this._noMipmap);
  59997. if (!this._texture) {
  59998. if (this._prefiltered) {
  59999. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  60000. }
  60001. else {
  60002. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  60003. }
  60004. }
  60005. };
  60006. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  60007. return this._textureMatrix;
  60008. };
  60009. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  60010. this._textureMatrix = value;
  60011. };
  60012. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60013. var texture = BABYLON.SerializationHelper.Parse(function () {
  60014. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  60015. }, parsedTexture, scene);
  60016. // Local Cubemaps
  60017. if (parsedTexture.boundingBoxPosition) {
  60018. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  60019. }
  60020. if (parsedTexture.boundingBoxSize) {
  60021. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  60022. }
  60023. // Animations
  60024. if (parsedTexture.animations) {
  60025. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  60026. var parsedAnimation = parsedTexture.animations[animationIndex];
  60027. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60028. }
  60029. }
  60030. return texture;
  60031. };
  60032. CubeTexture.prototype.clone = function () {
  60033. var _this = this;
  60034. return BABYLON.SerializationHelper.Clone(function () {
  60035. var scene = _this.getScene();
  60036. if (!scene) {
  60037. return _this;
  60038. }
  60039. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  60040. }, this);
  60041. };
  60042. return CubeTexture;
  60043. }(BABYLON.BaseTexture));
  60044. BABYLON.CubeTexture = CubeTexture;
  60045. })(BABYLON || (BABYLON = {}));
  60046. //# sourceMappingURL=babylon.cubeTexture.js.map
  60047. "use strict";
  60048. var BABYLON;
  60049. (function (BABYLON) {
  60050. var RenderTargetTexture = /** @class */ (function (_super) {
  60051. __extends(RenderTargetTexture, _super);
  60052. /**
  60053. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  60054. * or used a shadow, depth texture...
  60055. * @param name The friendly name of the texture
  60056. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  60057. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  60058. * @param generateMipMaps True if mip maps need to be generated after render.
  60059. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  60060. * @param type The type of the buffer in the RTT (int, half float, float...)
  60061. * @param isCube True if a cube texture needs to be created
  60062. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  60063. * @param generateDepthBuffer True to generate a depth buffer
  60064. * @param generateStencilBuffer True to generate a stencil buffer
  60065. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  60066. */
  60067. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  60068. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  60069. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60070. if (isCube === void 0) { isCube = false; }
  60071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60072. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  60073. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  60074. if (isMulti === void 0) { isMulti = false; }
  60075. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  60076. _this.isCube = isCube;
  60077. /**
  60078. * Use this list to define the list of mesh you want to render.
  60079. */
  60080. _this.renderList = new Array();
  60081. _this.renderParticles = true;
  60082. _this.renderSprites = false;
  60083. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  60084. _this.ignoreCameraViewport = false;
  60085. // Events
  60086. /**
  60087. * An event triggered when the texture is unbind.
  60088. */
  60089. _this.onBeforeBindObservable = new BABYLON.Observable();
  60090. /**
  60091. * An event triggered when the texture is unbind.
  60092. */
  60093. _this.onAfterUnbindObservable = new BABYLON.Observable();
  60094. /**
  60095. * An event triggered before rendering the texture
  60096. */
  60097. _this.onBeforeRenderObservable = new BABYLON.Observable();
  60098. /**
  60099. * An event triggered after rendering the texture
  60100. */
  60101. _this.onAfterRenderObservable = new BABYLON.Observable();
  60102. /**
  60103. * An event triggered after the texture clear
  60104. */
  60105. _this.onClearObservable = new BABYLON.Observable();
  60106. _this._currentRefreshId = -1;
  60107. _this._refreshRate = 1;
  60108. _this._samples = 1;
  60109. /**
  60110. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  60111. * It must define where the camera used to render the texture is set
  60112. */
  60113. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  60114. scene = _this.getScene();
  60115. if (!scene) {
  60116. return _this;
  60117. }
  60118. _this._engine = scene.getEngine();
  60119. _this.name = name;
  60120. _this.isRenderTarget = true;
  60121. _this._initialSizeParameter = size;
  60122. _this._processSizeParameter(size);
  60123. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  60124. });
  60125. _this._generateMipMaps = generateMipMaps ? true : false;
  60126. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  60127. // Rendering groups
  60128. _this._renderingManager = new BABYLON.RenderingManager(scene);
  60129. if (isMulti) {
  60130. return _this;
  60131. }
  60132. _this._renderTargetOptions = {
  60133. generateMipMaps: generateMipMaps,
  60134. type: type,
  60135. samplingMode: samplingMode,
  60136. generateDepthBuffer: generateDepthBuffer,
  60137. generateStencilBuffer: generateStencilBuffer
  60138. };
  60139. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  60140. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60141. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60142. }
  60143. if (isCube) {
  60144. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  60145. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  60146. _this._textureMatrix = BABYLON.Matrix.Identity();
  60147. }
  60148. else {
  60149. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  60150. }
  60151. return _this;
  60152. }
  60153. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  60154. get: function () {
  60155. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  60156. },
  60157. enumerable: true,
  60158. configurable: true
  60159. });
  60160. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  60161. get: function () {
  60162. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  60163. },
  60164. enumerable: true,
  60165. configurable: true
  60166. });
  60167. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  60168. get: function () {
  60169. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  60170. },
  60171. enumerable: true,
  60172. configurable: true
  60173. });
  60174. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  60175. set: function (callback) {
  60176. if (this._onAfterUnbindObserver) {
  60177. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  60178. }
  60179. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  60180. },
  60181. enumerable: true,
  60182. configurable: true
  60183. });
  60184. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  60185. set: function (callback) {
  60186. if (this._onBeforeRenderObserver) {
  60187. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60188. }
  60189. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60190. },
  60191. enumerable: true,
  60192. configurable: true
  60193. });
  60194. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  60195. set: function (callback) {
  60196. if (this._onAfterRenderObserver) {
  60197. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60198. }
  60199. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60200. },
  60201. enumerable: true,
  60202. configurable: true
  60203. });
  60204. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  60205. set: function (callback) {
  60206. if (this._onClearObserver) {
  60207. this.onClearObservable.remove(this._onClearObserver);
  60208. }
  60209. this._onClearObserver = this.onClearObservable.add(callback);
  60210. },
  60211. enumerable: true,
  60212. configurable: true
  60213. });
  60214. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  60215. get: function () {
  60216. return this._renderTargetOptions;
  60217. },
  60218. enumerable: true,
  60219. configurable: true
  60220. });
  60221. RenderTargetTexture.prototype._onRatioRescale = function () {
  60222. if (this._sizeRatio) {
  60223. this.resize(this._initialSizeParameter);
  60224. }
  60225. };
  60226. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  60227. get: function () {
  60228. return this._boundingBoxSize;
  60229. },
  60230. /**
  60231. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  60232. * When defined, the cubemap will switch to local mode
  60233. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  60234. * @example https://www.babylonjs-playground.com/#RNASML
  60235. */
  60236. set: function (value) {
  60237. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  60238. return;
  60239. }
  60240. this._boundingBoxSize = value;
  60241. var scene = this.getScene();
  60242. if (scene) {
  60243. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  60244. }
  60245. },
  60246. enumerable: true,
  60247. configurable: true
  60248. });
  60249. /**
  60250. * Creates a depth stencil texture.
  60251. * This is only available in WebGL 2 or with the depth texture extension available.
  60252. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  60253. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  60254. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  60255. */
  60256. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  60257. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  60258. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  60259. if (generateStencil === void 0) { generateStencil = false; }
  60260. if (!this.getScene()) {
  60261. return;
  60262. }
  60263. var engine = this.getScene().getEngine();
  60264. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  60265. bilinearFiltering: bilinearFiltering,
  60266. comparisonFunction: comparisonFunction,
  60267. generateStencil: generateStencil,
  60268. isCube: this.isCube
  60269. });
  60270. engine.setFrameBufferDepthStencilTexture(this);
  60271. };
  60272. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  60273. if (size.ratio) {
  60274. this._sizeRatio = size.ratio;
  60275. this._size = {
  60276. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  60277. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  60278. };
  60279. }
  60280. else {
  60281. this._size = size;
  60282. }
  60283. };
  60284. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  60285. get: function () {
  60286. return this._samples;
  60287. },
  60288. set: function (value) {
  60289. if (this._samples === value) {
  60290. return;
  60291. }
  60292. var scene = this.getScene();
  60293. if (!scene) {
  60294. return;
  60295. }
  60296. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  60297. },
  60298. enumerable: true,
  60299. configurable: true
  60300. });
  60301. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  60302. this._currentRefreshId = -1;
  60303. };
  60304. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  60305. get: function () {
  60306. return this._refreshRate;
  60307. },
  60308. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  60309. set: function (value) {
  60310. this._refreshRate = value;
  60311. this.resetRefreshCounter();
  60312. },
  60313. enumerable: true,
  60314. configurable: true
  60315. });
  60316. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  60317. if (!this._postProcessManager) {
  60318. var scene = this.getScene();
  60319. if (!scene) {
  60320. return;
  60321. }
  60322. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  60323. this._postProcesses = new Array();
  60324. }
  60325. this._postProcesses.push(postProcess);
  60326. this._postProcesses[0].autoClear = false;
  60327. };
  60328. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  60329. if (!this._postProcesses) {
  60330. return;
  60331. }
  60332. if (dispose) {
  60333. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  60334. var postProcess = _a[_i];
  60335. postProcess.dispose();
  60336. }
  60337. }
  60338. this._postProcesses = [];
  60339. };
  60340. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  60341. if (!this._postProcesses) {
  60342. return;
  60343. }
  60344. var index = this._postProcesses.indexOf(postProcess);
  60345. if (index === -1) {
  60346. return;
  60347. }
  60348. this._postProcesses.splice(index, 1);
  60349. if (this._postProcesses.length > 0) {
  60350. this._postProcesses[0].autoClear = false;
  60351. }
  60352. };
  60353. RenderTargetTexture.prototype._shouldRender = function () {
  60354. if (this._currentRefreshId === -1) {
  60355. this._currentRefreshId = 1;
  60356. return true;
  60357. }
  60358. if (this.refreshRate === this._currentRefreshId) {
  60359. this._currentRefreshId = 1;
  60360. return true;
  60361. }
  60362. this._currentRefreshId++;
  60363. return false;
  60364. };
  60365. RenderTargetTexture.prototype.getRenderSize = function () {
  60366. if (this._size.width) {
  60367. return this._size.width;
  60368. }
  60369. return this._size;
  60370. };
  60371. RenderTargetTexture.prototype.getRenderWidth = function () {
  60372. if (this._size.width) {
  60373. return this._size.width;
  60374. }
  60375. return this._size;
  60376. };
  60377. RenderTargetTexture.prototype.getRenderHeight = function () {
  60378. if (this._size.width) {
  60379. return this._size.height;
  60380. }
  60381. return this._size;
  60382. };
  60383. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  60384. get: function () {
  60385. return true;
  60386. },
  60387. enumerable: true,
  60388. configurable: true
  60389. });
  60390. RenderTargetTexture.prototype.scale = function (ratio) {
  60391. var newSize = this.getRenderSize() * ratio;
  60392. this.resize(newSize);
  60393. };
  60394. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  60395. if (this.isCube) {
  60396. return this._textureMatrix;
  60397. }
  60398. return _super.prototype.getReflectionTextureMatrix.call(this);
  60399. };
  60400. RenderTargetTexture.prototype.resize = function (size) {
  60401. this.releaseInternalTexture();
  60402. var scene = this.getScene();
  60403. if (!scene) {
  60404. return;
  60405. }
  60406. this._processSizeParameter(size);
  60407. if (this.isCube) {
  60408. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  60409. }
  60410. else {
  60411. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  60412. }
  60413. };
  60414. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  60415. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  60416. if (dumpForDebug === void 0) { dumpForDebug = false; }
  60417. var scene = this.getScene();
  60418. if (!scene) {
  60419. return;
  60420. }
  60421. var engine = scene.getEngine();
  60422. if (this.useCameraPostProcesses !== undefined) {
  60423. useCameraPostProcess = this.useCameraPostProcesses;
  60424. }
  60425. if (this._waitingRenderList) {
  60426. this.renderList = [];
  60427. for (var index = 0; index < this._waitingRenderList.length; index++) {
  60428. var id = this._waitingRenderList[index];
  60429. var mesh_1 = scene.getMeshByID(id);
  60430. if (mesh_1) {
  60431. this.renderList.push(mesh_1);
  60432. }
  60433. }
  60434. delete this._waitingRenderList;
  60435. }
  60436. // Is predicate defined?
  60437. if (this.renderListPredicate) {
  60438. if (this.renderList) {
  60439. this.renderList.splice(0); // Clear previous renderList
  60440. }
  60441. else {
  60442. this.renderList = [];
  60443. }
  60444. var scene = this.getScene();
  60445. if (!scene) {
  60446. return;
  60447. }
  60448. var sceneMeshes = scene.meshes;
  60449. for (var index = 0; index < sceneMeshes.length; index++) {
  60450. var mesh = sceneMeshes[index];
  60451. if (this.renderListPredicate(mesh)) {
  60452. this.renderList.push(mesh);
  60453. }
  60454. }
  60455. }
  60456. this.onBeforeBindObservable.notifyObservers(this);
  60457. // Set custom projection.
  60458. // Needs to be before binding to prevent changing the aspect ratio.
  60459. var camera;
  60460. if (this.activeCamera) {
  60461. camera = this.activeCamera;
  60462. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  60463. if (this.activeCamera !== scene.activeCamera) {
  60464. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  60465. }
  60466. }
  60467. else {
  60468. camera = scene.activeCamera;
  60469. if (camera) {
  60470. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  60471. }
  60472. }
  60473. // Prepare renderingManager
  60474. this._renderingManager.reset();
  60475. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  60476. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  60477. var sceneRenderId = scene.getRenderId();
  60478. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  60479. var mesh = currentRenderList[meshIndex];
  60480. if (mesh) {
  60481. if (!mesh.isReady(this.refreshRate === 0)) {
  60482. this.resetRefreshCounter();
  60483. continue;
  60484. }
  60485. mesh._preActivateForIntermediateRendering(sceneRenderId);
  60486. var isMasked = void 0;
  60487. if (!this.renderList && camera) {
  60488. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  60489. }
  60490. else {
  60491. isMasked = false;
  60492. }
  60493. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  60494. mesh._activate(sceneRenderId);
  60495. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  60496. var subMesh = mesh.subMeshes[subIndex];
  60497. scene._activeIndices.addCount(subMesh.indexCount, false);
  60498. this._renderingManager.dispatch(subMesh, mesh);
  60499. }
  60500. }
  60501. }
  60502. }
  60503. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  60504. var particleSystem = scene.particleSystems[particleIndex];
  60505. var emitter = particleSystem.emitter;
  60506. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  60507. continue;
  60508. }
  60509. if (currentRenderList.indexOf(emitter) >= 0) {
  60510. this._renderingManager.dispatchParticles(particleSystem);
  60511. }
  60512. }
  60513. if (this.isCube) {
  60514. for (var face = 0; face < 6; face++) {
  60515. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  60516. scene.incrementRenderId();
  60517. scene.resetCachedMaterial();
  60518. }
  60519. }
  60520. else {
  60521. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  60522. }
  60523. this.onAfterUnbindObservable.notifyObservers(this);
  60524. if (scene.activeCamera) {
  60525. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  60526. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  60527. }
  60528. engine.setViewport(scene.activeCamera.viewport);
  60529. }
  60530. scene.resetCachedMaterial();
  60531. };
  60532. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  60533. var minimum = 128;
  60534. var x = renderDimension * scale;
  60535. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  60536. // Ensure we don't exceed the render dimension (while staying POT)
  60537. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  60538. };
  60539. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  60540. var _this = this;
  60541. if (!this._texture) {
  60542. return;
  60543. }
  60544. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  60545. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  60546. });
  60547. };
  60548. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  60549. var scene = this.getScene();
  60550. if (!scene) {
  60551. return;
  60552. }
  60553. var engine = scene.getEngine();
  60554. if (!this._texture) {
  60555. return;
  60556. }
  60557. // Bind
  60558. if (this._postProcessManager) {
  60559. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  60560. }
  60561. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  60562. if (this._texture) {
  60563. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  60564. }
  60565. }
  60566. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  60567. // Clear
  60568. if (this.onClearObservable.hasObservers()) {
  60569. this.onClearObservable.notifyObservers(engine);
  60570. }
  60571. else {
  60572. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  60573. }
  60574. if (!this._doNotChangeAspectRatio) {
  60575. scene.updateTransformMatrix(true);
  60576. }
  60577. // Render
  60578. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  60579. if (this._postProcessManager) {
  60580. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  60581. }
  60582. else if (useCameraPostProcess) {
  60583. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  60584. }
  60585. if (!this._doNotChangeAspectRatio) {
  60586. scene.updateTransformMatrix(true);
  60587. }
  60588. // Dump ?
  60589. if (dumpForDebug) {
  60590. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  60591. }
  60592. // Unbind
  60593. if (!this.isCube || faceIndex === 5) {
  60594. if (this.isCube) {
  60595. if (faceIndex === 5) {
  60596. engine.generateMipMapsForCubemap(this._texture);
  60597. }
  60598. }
  60599. this.unbindFrameBuffer(engine, faceIndex);
  60600. }
  60601. else {
  60602. this.onAfterRenderObservable.notifyObservers(faceIndex);
  60603. }
  60604. };
  60605. /**
  60606. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  60607. * This allowed control for front to back rendering or reversly depending of the special needs.
  60608. *
  60609. * @param renderingGroupId The rendering group id corresponding to its index
  60610. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  60611. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  60612. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  60613. */
  60614. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  60615. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  60616. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  60617. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  60618. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  60619. };
  60620. /**
  60621. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  60622. *
  60623. * @param renderingGroupId The rendering group id corresponding to its index
  60624. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  60625. */
  60626. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  60627. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  60628. };
  60629. RenderTargetTexture.prototype.clone = function () {
  60630. var textureSize = this.getSize();
  60631. 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);
  60632. // Base texture
  60633. newTexture.hasAlpha = this.hasAlpha;
  60634. newTexture.level = this.level;
  60635. // RenderTarget Texture
  60636. newTexture.coordinatesMode = this.coordinatesMode;
  60637. if (this.renderList) {
  60638. newTexture.renderList = this.renderList.slice(0);
  60639. }
  60640. return newTexture;
  60641. };
  60642. RenderTargetTexture.prototype.serialize = function () {
  60643. if (!this.name) {
  60644. return null;
  60645. }
  60646. var serializationObject = _super.prototype.serialize.call(this);
  60647. serializationObject.renderTargetSize = this.getRenderSize();
  60648. serializationObject.renderList = [];
  60649. if (this.renderList) {
  60650. for (var index = 0; index < this.renderList.length; index++) {
  60651. serializationObject.renderList.push(this.renderList[index].id);
  60652. }
  60653. }
  60654. return serializationObject;
  60655. };
  60656. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  60657. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  60658. var objBuffer = this.getInternalTexture();
  60659. var scene = this.getScene();
  60660. if (objBuffer && scene) {
  60661. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  60662. }
  60663. };
  60664. RenderTargetTexture.prototype.dispose = function () {
  60665. if (this._postProcessManager) {
  60666. this._postProcessManager.dispose();
  60667. this._postProcessManager = null;
  60668. }
  60669. this.clearPostProcesses(true);
  60670. if (this._resizeObserver) {
  60671. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  60672. this._resizeObserver = null;
  60673. }
  60674. this.renderList = null;
  60675. // Remove from custom render targets
  60676. var scene = this.getScene();
  60677. if (!scene) {
  60678. return;
  60679. }
  60680. var index = scene.customRenderTargets.indexOf(this);
  60681. if (index >= 0) {
  60682. scene.customRenderTargets.splice(index, 1);
  60683. }
  60684. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  60685. var camera = _a[_i];
  60686. index = camera.customRenderTargets.indexOf(this);
  60687. if (index >= 0) {
  60688. camera.customRenderTargets.splice(index, 1);
  60689. }
  60690. }
  60691. _super.prototype.dispose.call(this);
  60692. };
  60693. RenderTargetTexture.prototype._rebuild = function () {
  60694. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  60695. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  60696. }
  60697. if (this._postProcessManager) {
  60698. this._postProcessManager._rebuild();
  60699. }
  60700. };
  60701. /**
  60702. * Clear the info related to rendering groups preventing retention point in material dispose.
  60703. */
  60704. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  60705. if (this._renderingManager) {
  60706. this._renderingManager.freeRenderingGroups();
  60707. }
  60708. };
  60709. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  60710. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  60711. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  60712. return RenderTargetTexture;
  60713. }(BABYLON.Texture));
  60714. BABYLON.RenderTargetTexture = RenderTargetTexture;
  60715. })(BABYLON || (BABYLON = {}));
  60716. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  60717. "use strict";
  60718. var BABYLON;
  60719. (function (BABYLON) {
  60720. ;
  60721. var MultiRenderTarget = /** @class */ (function (_super) {
  60722. __extends(MultiRenderTarget, _super);
  60723. function MultiRenderTarget(name, size, count, scene, options) {
  60724. var _this = this;
  60725. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  60726. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  60727. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  60728. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  60729. _this._engine = scene.getEngine();
  60730. if (!_this.isSupported) {
  60731. _this.dispose();
  60732. return;
  60733. }
  60734. var types = [];
  60735. var samplingModes = [];
  60736. for (var i = 0; i < count; i++) {
  60737. if (options && options.types && options.types[i] !== undefined) {
  60738. types.push(options.types[i]);
  60739. }
  60740. else {
  60741. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60742. }
  60743. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  60744. samplingModes.push(options.samplingModes[i]);
  60745. }
  60746. else {
  60747. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60748. }
  60749. }
  60750. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  60751. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  60752. _this._size = size;
  60753. _this._multiRenderTargetOptions = {
  60754. samplingModes: samplingModes,
  60755. generateMipMaps: generateMipMaps,
  60756. generateDepthBuffer: generateDepthBuffer,
  60757. generateStencilBuffer: generateStencilBuffer,
  60758. generateDepthTexture: generateDepthTexture,
  60759. types: types,
  60760. textureCount: count
  60761. };
  60762. _this._createInternalTextures();
  60763. _this._createTextures();
  60764. return _this;
  60765. }
  60766. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  60767. get: function () {
  60768. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  60769. },
  60770. enumerable: true,
  60771. configurable: true
  60772. });
  60773. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  60774. get: function () {
  60775. return this._textures;
  60776. },
  60777. enumerable: true,
  60778. configurable: true
  60779. });
  60780. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  60781. get: function () {
  60782. return this._textures[this._textures.length - 1];
  60783. },
  60784. enumerable: true,
  60785. configurable: true
  60786. });
  60787. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  60788. set: function (wrap) {
  60789. if (this._textures) {
  60790. for (var i = 0; i < this._textures.length; i++) {
  60791. this._textures[i].wrapU = wrap;
  60792. }
  60793. }
  60794. },
  60795. enumerable: true,
  60796. configurable: true
  60797. });
  60798. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  60799. set: function (wrap) {
  60800. if (this._textures) {
  60801. for (var i = 0; i < this._textures.length; i++) {
  60802. this._textures[i].wrapV = wrap;
  60803. }
  60804. }
  60805. },
  60806. enumerable: true,
  60807. configurable: true
  60808. });
  60809. MultiRenderTarget.prototype._rebuild = function () {
  60810. this.releaseInternalTextures();
  60811. this._createInternalTextures();
  60812. for (var i = 0; i < this._internalTextures.length; i++) {
  60813. var texture = this._textures[i];
  60814. texture._texture = this._internalTextures[i];
  60815. }
  60816. // Keeps references to frame buffer and stencil/depth buffer
  60817. this._texture = this._internalTextures[0];
  60818. };
  60819. MultiRenderTarget.prototype._createInternalTextures = function () {
  60820. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  60821. };
  60822. MultiRenderTarget.prototype._createTextures = function () {
  60823. this._textures = [];
  60824. for (var i = 0; i < this._internalTextures.length; i++) {
  60825. var texture = new BABYLON.Texture(null, this.getScene());
  60826. texture._texture = this._internalTextures[i];
  60827. this._textures.push(texture);
  60828. }
  60829. // Keeps references to frame buffer and stencil/depth buffer
  60830. this._texture = this._internalTextures[0];
  60831. };
  60832. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  60833. get: function () {
  60834. return this._samples;
  60835. },
  60836. set: function (value) {
  60837. if (this._samples === value) {
  60838. return;
  60839. }
  60840. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  60841. },
  60842. enumerable: true,
  60843. configurable: true
  60844. });
  60845. MultiRenderTarget.prototype.resize = function (size) {
  60846. this.releaseInternalTextures();
  60847. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  60848. this._createInternalTextures();
  60849. };
  60850. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  60851. var _this = this;
  60852. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  60853. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  60854. });
  60855. };
  60856. MultiRenderTarget.prototype.dispose = function () {
  60857. this.releaseInternalTextures();
  60858. _super.prototype.dispose.call(this);
  60859. };
  60860. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  60861. if (!this._internalTextures) {
  60862. return;
  60863. }
  60864. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  60865. if (this._internalTextures[i] !== undefined) {
  60866. this._internalTextures[i].dispose();
  60867. this._internalTextures.splice(i, 1);
  60868. }
  60869. }
  60870. };
  60871. return MultiRenderTarget;
  60872. }(BABYLON.RenderTargetTexture));
  60873. BABYLON.MultiRenderTarget = MultiRenderTarget;
  60874. })(BABYLON || (BABYLON = {}));
  60875. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  60876. "use strict";
  60877. var BABYLON;
  60878. (function (BABYLON) {
  60879. var MirrorTexture = /** @class */ (function (_super) {
  60880. __extends(MirrorTexture, _super);
  60881. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  60882. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60884. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  60885. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  60886. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  60887. _this._transformMatrix = BABYLON.Matrix.Zero();
  60888. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  60889. _this._adaptiveBlurKernel = 0;
  60890. _this._blurKernelX = 0;
  60891. _this._blurKernelY = 0;
  60892. _this._blurRatio = 1.0;
  60893. _this.ignoreCameraViewport = true;
  60894. _this.onBeforeRenderObservable.add(function () {
  60895. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  60896. _this._savedViewMatrix = scene.getViewMatrix();
  60897. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  60898. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  60899. scene.clipPlane = _this.mirrorPlane;
  60900. scene.getEngine().cullBackFaces = false;
  60901. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  60902. });
  60903. _this.onAfterRenderObservable.add(function () {
  60904. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  60905. scene.getEngine().cullBackFaces = true;
  60906. scene._mirroredCameraPosition = null;
  60907. delete scene.clipPlane;
  60908. });
  60909. return _this;
  60910. }
  60911. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  60912. get: function () {
  60913. return this._blurRatio;
  60914. },
  60915. set: function (value) {
  60916. if (this._blurRatio === value) {
  60917. return;
  60918. }
  60919. this._blurRatio = value;
  60920. this._preparePostProcesses();
  60921. },
  60922. enumerable: true,
  60923. configurable: true
  60924. });
  60925. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  60926. set: function (value) {
  60927. this._adaptiveBlurKernel = value;
  60928. this._autoComputeBlurKernel();
  60929. },
  60930. enumerable: true,
  60931. configurable: true
  60932. });
  60933. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  60934. set: function (value) {
  60935. this.blurKernelX = value;
  60936. this.blurKernelY = value;
  60937. },
  60938. enumerable: true,
  60939. configurable: true
  60940. });
  60941. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  60942. get: function () {
  60943. return this._blurKernelX;
  60944. },
  60945. set: function (value) {
  60946. if (this._blurKernelX === value) {
  60947. return;
  60948. }
  60949. this._blurKernelX = value;
  60950. this._preparePostProcesses();
  60951. },
  60952. enumerable: true,
  60953. configurable: true
  60954. });
  60955. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  60956. get: function () {
  60957. return this._blurKernelY;
  60958. },
  60959. set: function (value) {
  60960. if (this._blurKernelY === value) {
  60961. return;
  60962. }
  60963. this._blurKernelY = value;
  60964. this._preparePostProcesses();
  60965. },
  60966. enumerable: true,
  60967. configurable: true
  60968. });
  60969. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  60970. var engine = this.getScene().getEngine();
  60971. var dw = this.getRenderWidth() / engine.getRenderWidth();
  60972. var dh = this.getRenderHeight() / engine.getRenderHeight();
  60973. this.blurKernelX = this._adaptiveBlurKernel * dw;
  60974. this.blurKernelY = this._adaptiveBlurKernel * dh;
  60975. };
  60976. MirrorTexture.prototype._onRatioRescale = function () {
  60977. if (this._sizeRatio) {
  60978. this.resize(this._initialSizeParameter);
  60979. if (!this._adaptiveBlurKernel) {
  60980. this._preparePostProcesses();
  60981. }
  60982. }
  60983. if (this._adaptiveBlurKernel) {
  60984. this._autoComputeBlurKernel();
  60985. }
  60986. };
  60987. MirrorTexture.prototype._preparePostProcesses = function () {
  60988. this.clearPostProcesses(true);
  60989. if (this._blurKernelX && this._blurKernelY) {
  60990. var engine = this.getScene().getEngine();
  60991. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60992. 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);
  60993. this._blurX.autoClear = false;
  60994. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  60995. this._blurX.inputTexture = this._texture;
  60996. }
  60997. else {
  60998. this._blurX.alwaysForcePOT = true;
  60999. }
  61000. 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);
  61001. this._blurY.autoClear = false;
  61002. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  61003. this.addPostProcess(this._blurX);
  61004. this.addPostProcess(this._blurY);
  61005. }
  61006. else {
  61007. if (this._blurY) {
  61008. this.removePostProcess(this._blurY);
  61009. this._blurY.dispose();
  61010. this._blurY = null;
  61011. }
  61012. if (this._blurX) {
  61013. this.removePostProcess(this._blurX);
  61014. this._blurX.dispose();
  61015. this._blurX = null;
  61016. }
  61017. }
  61018. };
  61019. MirrorTexture.prototype.clone = function () {
  61020. var scene = this.getScene();
  61021. if (!scene) {
  61022. return this;
  61023. }
  61024. var textureSize = this.getSize();
  61025. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  61026. // Base texture
  61027. newTexture.hasAlpha = this.hasAlpha;
  61028. newTexture.level = this.level;
  61029. // Mirror Texture
  61030. newTexture.mirrorPlane = this.mirrorPlane.clone();
  61031. if (this.renderList) {
  61032. newTexture.renderList = this.renderList.slice(0);
  61033. }
  61034. return newTexture;
  61035. };
  61036. MirrorTexture.prototype.serialize = function () {
  61037. if (!this.name) {
  61038. return null;
  61039. }
  61040. var serializationObject = _super.prototype.serialize.call(this);
  61041. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  61042. return serializationObject;
  61043. };
  61044. return MirrorTexture;
  61045. }(BABYLON.RenderTargetTexture));
  61046. BABYLON.MirrorTexture = MirrorTexture;
  61047. })(BABYLON || (BABYLON = {}));
  61048. //# sourceMappingURL=babylon.mirrorTexture.js.map
  61049. "use strict";
  61050. var BABYLON;
  61051. (function (BABYLON) {
  61052. /**
  61053. * Creates a refraction texture used by refraction channel of the standard material.
  61054. * @param name the texture name
  61055. * @param size size of the underlying texture
  61056. * @param scene root scene
  61057. */
  61058. var RefractionTexture = /** @class */ (function (_super) {
  61059. __extends(RefractionTexture, _super);
  61060. function RefractionTexture(name, size, scene, generateMipMaps) {
  61061. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  61062. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  61063. _this.depth = 2.0;
  61064. _this.onBeforeRenderObservable.add(function () {
  61065. scene.clipPlane = _this.refractionPlane;
  61066. });
  61067. _this.onAfterRenderObservable.add(function () {
  61068. delete scene.clipPlane;
  61069. });
  61070. return _this;
  61071. }
  61072. RefractionTexture.prototype.clone = function () {
  61073. var scene = this.getScene();
  61074. if (!scene) {
  61075. return this;
  61076. }
  61077. var textureSize = this.getSize();
  61078. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  61079. // Base texture
  61080. newTexture.hasAlpha = this.hasAlpha;
  61081. newTexture.level = this.level;
  61082. // Refraction Texture
  61083. newTexture.refractionPlane = this.refractionPlane.clone();
  61084. if (this.renderList) {
  61085. newTexture.renderList = this.renderList.slice(0);
  61086. }
  61087. newTexture.depth = this.depth;
  61088. return newTexture;
  61089. };
  61090. RefractionTexture.prototype.serialize = function () {
  61091. if (!this.name) {
  61092. return null;
  61093. }
  61094. var serializationObject = _super.prototype.serialize.call(this);
  61095. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  61096. serializationObject.depth = this.depth;
  61097. return serializationObject;
  61098. };
  61099. return RefractionTexture;
  61100. }(BABYLON.RenderTargetTexture));
  61101. BABYLON.RefractionTexture = RefractionTexture;
  61102. })(BABYLON || (BABYLON = {}));
  61103. //# sourceMappingURL=babylon.refractionTexture.js.map
  61104. "use strict";
  61105. var BABYLON;
  61106. (function (BABYLON) {
  61107. /**
  61108. * A class extending {BABYLON.Texture} allowing drawing on a texture
  61109. * @see http://doc.babylonjs.com/how_to/dynamictexture
  61110. */
  61111. var DynamicTexture = /** @class */ (function (_super) {
  61112. __extends(DynamicTexture, _super);
  61113. /**
  61114. * Creates a {BABYLON.DynamicTexture}
  61115. * @param name defines the name of the texture
  61116. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  61117. * @param scene defines the scene where you want the texture
  61118. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  61119. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  61120. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  61121. */
  61122. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  61123. if (scene === void 0) { scene = null; }
  61124. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61125. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61126. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  61127. _this.name = name;
  61128. _this._engine = _this.getScene().getEngine();
  61129. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61130. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61131. _this._generateMipMaps = generateMipMaps;
  61132. if (options.getContext) {
  61133. _this._canvas = options;
  61134. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  61135. }
  61136. else {
  61137. _this._canvas = document.createElement("canvas");
  61138. if (options.width) {
  61139. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  61140. }
  61141. else {
  61142. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  61143. }
  61144. }
  61145. var textureSize = _this.getSize();
  61146. _this._canvas.width = textureSize.width;
  61147. _this._canvas.height = textureSize.height;
  61148. _this._context = _this._canvas.getContext("2d");
  61149. return _this;
  61150. }
  61151. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  61152. /**
  61153. * Gets the current state of canRescale
  61154. */
  61155. get: function () {
  61156. return true;
  61157. },
  61158. enumerable: true,
  61159. configurable: true
  61160. });
  61161. DynamicTexture.prototype._recreate = function (textureSize) {
  61162. this._canvas.width = textureSize.width;
  61163. this._canvas.height = textureSize.height;
  61164. this.releaseInternalTexture();
  61165. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  61166. };
  61167. /**
  61168. * Scales the texture
  61169. * @param ratio the scale factor to apply to both width and height
  61170. */
  61171. DynamicTexture.prototype.scale = function (ratio) {
  61172. var textureSize = this.getSize();
  61173. textureSize.width *= ratio;
  61174. textureSize.height *= ratio;
  61175. this._recreate(textureSize);
  61176. };
  61177. /**
  61178. * Resizes the texture
  61179. * @param width the new width
  61180. * @param height the new height
  61181. */
  61182. DynamicTexture.prototype.scaleTo = function (width, height) {
  61183. var textureSize = this.getSize();
  61184. textureSize.width = width;
  61185. textureSize.height = height;
  61186. this._recreate(textureSize);
  61187. };
  61188. /**
  61189. * Gets the context of the canvas used by the texture
  61190. * @returns the canvas context of the dynamic texture
  61191. */
  61192. DynamicTexture.prototype.getContext = function () {
  61193. return this._context;
  61194. };
  61195. /**
  61196. * Clears the texture
  61197. */
  61198. DynamicTexture.prototype.clear = function () {
  61199. var size = this.getSize();
  61200. this._context.fillRect(0, 0, size.width, size.height);
  61201. };
  61202. /**
  61203. * Updates the texture
  61204. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  61205. */
  61206. DynamicTexture.prototype.update = function (invertY) {
  61207. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  61208. };
  61209. /**
  61210. * Draws text onto the texture
  61211. * @param text defines the text to be drawn
  61212. * @param x defines the placement of the text from the left
  61213. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  61214. * @param font defines the font to be used with font-style, font-size, font-name
  61215. * @param color defines the color used for the text
  61216. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  61217. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  61218. * @param update defines whether texture is immediately update (default is true)
  61219. */
  61220. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  61221. if (update === void 0) { update = true; }
  61222. var size = this.getSize();
  61223. if (clearColor) {
  61224. this._context.fillStyle = clearColor;
  61225. this._context.fillRect(0, 0, size.width, size.height);
  61226. }
  61227. this._context.font = font;
  61228. if (x === null || x === undefined) {
  61229. var textSize = this._context.measureText(text);
  61230. x = (size.width - textSize.width) / 2;
  61231. }
  61232. if (y === null || y === undefined) {
  61233. var fontSize = parseInt((font.replace(/\D/g, '')));
  61234. ;
  61235. y = (size.height / 2) + (fontSize / 3.65);
  61236. }
  61237. this._context.fillStyle = color;
  61238. this._context.fillText(text, x, y);
  61239. if (update) {
  61240. this.update(invertY);
  61241. }
  61242. };
  61243. /**
  61244. * Clones the texture
  61245. * @returns the clone of the texture.
  61246. */
  61247. DynamicTexture.prototype.clone = function () {
  61248. var scene = this.getScene();
  61249. if (!scene) {
  61250. return this;
  61251. }
  61252. var textureSize = this.getSize();
  61253. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  61254. // Base texture
  61255. newTexture.hasAlpha = this.hasAlpha;
  61256. newTexture.level = this.level;
  61257. // Dynamic Texture
  61258. newTexture.wrapU = this.wrapU;
  61259. newTexture.wrapV = this.wrapV;
  61260. return newTexture;
  61261. };
  61262. /** @ignore */
  61263. DynamicTexture.prototype._rebuild = function () {
  61264. this.update();
  61265. };
  61266. return DynamicTexture;
  61267. }(BABYLON.Texture));
  61268. BABYLON.DynamicTexture = DynamicTexture;
  61269. })(BABYLON || (BABYLON = {}));
  61270. //# sourceMappingURL=babylon.dynamicTexture.js.map
  61271. "use strict";
  61272. var BABYLON;
  61273. (function (BABYLON) {
  61274. var VideoTexture = /** @class */ (function (_super) {
  61275. __extends(VideoTexture, _super);
  61276. /**
  61277. * Creates a video texture.
  61278. * Sample : https://doc.babylonjs.com/how_to/video_texture
  61279. * @param {string | null} name optional name, will detect from video source, if not defined
  61280. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  61281. * @param {BABYLON.Scene} scene is obviously the current scene.
  61282. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  61283. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  61284. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  61285. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  61286. */
  61287. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  61288. if (generateMipMaps === void 0) { generateMipMaps = false; }
  61289. if (invertY === void 0) { invertY = false; }
  61290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61291. if (settings === void 0) { settings = {
  61292. autoPlay: true,
  61293. loop: true,
  61294. autoUpdateTexture: true,
  61295. }; }
  61296. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  61297. _this._createInternalTexture = function () {
  61298. if (_this._texture != null) {
  61299. return;
  61300. }
  61301. if (!_this._engine.needPOTTextures ||
  61302. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  61303. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61304. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61305. }
  61306. else {
  61307. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61308. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61309. _this._generateMipMaps = false;
  61310. }
  61311. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  61312. _this._texture.isReady = true;
  61313. _this._updateInternalTexture();
  61314. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  61315. _this.onLoadObservable.notifyObservers(_this);
  61316. }
  61317. };
  61318. _this.reset = function () {
  61319. if (_this._texture == null) {
  61320. return;
  61321. }
  61322. _this._texture.dispose();
  61323. _this._texture = null;
  61324. };
  61325. _this._updateInternalTexture = function (e) {
  61326. if (_this._texture == null || !_this._texture.isReady) {
  61327. return;
  61328. }
  61329. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  61330. return;
  61331. }
  61332. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  61333. };
  61334. _this._engine = _this.getScene().getEngine();
  61335. _this._generateMipMaps = generateMipMaps;
  61336. _this._samplingMode = samplingMode;
  61337. _this.autoUpdateTexture = settings.autoUpdateTexture;
  61338. _this.name = name || _this._getName(src);
  61339. _this.video = _this._getVideo(src);
  61340. if (settings.autoPlay !== undefined) {
  61341. _this.video.autoplay = settings.autoPlay;
  61342. }
  61343. if (settings.loop !== undefined) {
  61344. _this.video.loop = settings.loop;
  61345. }
  61346. _this.video.addEventListener("canplay", _this._createInternalTexture);
  61347. _this.video.addEventListener("paused", _this._updateInternalTexture);
  61348. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  61349. _this.video.addEventListener("emptied", _this.reset);
  61350. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  61351. _this._createInternalTexture();
  61352. }
  61353. return _this;
  61354. }
  61355. VideoTexture.prototype._getName = function (src) {
  61356. if (src instanceof HTMLVideoElement) {
  61357. return src.currentSrc;
  61358. }
  61359. if (typeof src === "object") {
  61360. return src.toString();
  61361. }
  61362. return src;
  61363. };
  61364. ;
  61365. VideoTexture.prototype._getVideo = function (src) {
  61366. if (src instanceof HTMLVideoElement) {
  61367. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  61368. return src;
  61369. }
  61370. var video = document.createElement("video");
  61371. if (typeof src === "string") {
  61372. BABYLON.Tools.SetCorsBehavior(src, video);
  61373. video.src = src;
  61374. }
  61375. else {
  61376. BABYLON.Tools.SetCorsBehavior(src[0], video);
  61377. src.forEach(function (url) {
  61378. var source = document.createElement("source");
  61379. source.src = url;
  61380. video.appendChild(source);
  61381. });
  61382. }
  61383. return video;
  61384. };
  61385. ;
  61386. /**
  61387. * Internal method to initiate `update`.
  61388. */
  61389. VideoTexture.prototype._rebuild = function () {
  61390. this.update();
  61391. };
  61392. /**
  61393. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  61394. */
  61395. VideoTexture.prototype.update = function () {
  61396. if (!this.autoUpdateTexture) {
  61397. // Expecting user to call `updateTexture` manually
  61398. return;
  61399. }
  61400. this.updateTexture(true);
  61401. };
  61402. /**
  61403. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  61404. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  61405. */
  61406. VideoTexture.prototype.updateTexture = function (isVisible) {
  61407. if (!isVisible) {
  61408. return;
  61409. }
  61410. if (this.video.paused) {
  61411. return;
  61412. }
  61413. this._updateInternalTexture();
  61414. };
  61415. /**
  61416. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  61417. * @param url New url.
  61418. */
  61419. VideoTexture.prototype.updateURL = function (url) {
  61420. this.video.src = url;
  61421. };
  61422. VideoTexture.prototype.dispose = function () {
  61423. _super.prototype.dispose.call(this);
  61424. this.video.removeEventListener("canplay", this._createInternalTexture);
  61425. this.video.removeEventListener("paused", this._updateInternalTexture);
  61426. this.video.removeEventListener("seeked", this._updateInternalTexture);
  61427. this.video.removeEventListener("emptied", this.reset);
  61428. this.video.pause();
  61429. };
  61430. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  61431. var video = document.createElement("video");
  61432. var constraintsDeviceId;
  61433. if (constraints && constraints.deviceId) {
  61434. constraintsDeviceId = {
  61435. exact: constraints.deviceId,
  61436. };
  61437. }
  61438. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  61439. if (navigator.mediaDevices) {
  61440. navigator.mediaDevices.getUserMedia({ video: constraints })
  61441. .then(function (stream) {
  61442. if (video.mozSrcObject !== undefined) {
  61443. // hack for Firefox < 19
  61444. video.mozSrcObject = stream;
  61445. }
  61446. else {
  61447. video.srcObject = stream;
  61448. }
  61449. var onPlaying = function () {
  61450. if (onReady) {
  61451. onReady(new VideoTexture("video", video, scene, true, true));
  61452. }
  61453. video.removeEventListener("playing", onPlaying);
  61454. };
  61455. video.addEventListener("playing", onPlaying);
  61456. video.play();
  61457. })
  61458. .catch(function (err) {
  61459. BABYLON.Tools.Error(err.name);
  61460. });
  61461. }
  61462. else {
  61463. navigator.getUserMedia =
  61464. navigator.getUserMedia ||
  61465. navigator.webkitGetUserMedia ||
  61466. navigator.mozGetUserMedia ||
  61467. navigator.msGetUserMedia;
  61468. if (navigator.getUserMedia) {
  61469. navigator.getUserMedia({
  61470. video: {
  61471. deviceId: constraintsDeviceId,
  61472. width: {
  61473. min: (constraints && constraints.minWidth) || 256,
  61474. max: (constraints && constraints.maxWidth) || 640,
  61475. },
  61476. height: {
  61477. min: (constraints && constraints.minHeight) || 256,
  61478. max: (constraints && constraints.maxHeight) || 480,
  61479. },
  61480. },
  61481. }, function (stream) {
  61482. if (video.mozSrcObject !== undefined) {
  61483. // hack for Firefox < 19
  61484. video.mozSrcObject = stream;
  61485. }
  61486. else {
  61487. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  61488. }
  61489. video.play();
  61490. if (onReady) {
  61491. onReady(new VideoTexture("video", video, scene, true, true));
  61492. }
  61493. }, function (e) {
  61494. BABYLON.Tools.Error(e.name);
  61495. });
  61496. }
  61497. }
  61498. };
  61499. return VideoTexture;
  61500. }(BABYLON.Texture));
  61501. BABYLON.VideoTexture = VideoTexture;
  61502. })(BABYLON || (BABYLON = {}));
  61503. //# sourceMappingURL=babylon.videoTexture.js.map
  61504. "use strict";
  61505. var BABYLON;
  61506. (function (BABYLON) {
  61507. var RawTexture = /** @class */ (function (_super) {
  61508. __extends(RawTexture, _super);
  61509. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  61510. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61511. if (invertY === void 0) { invertY = false; }
  61512. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61513. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61514. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  61515. _this.format = format;
  61516. _this._engine = scene.getEngine();
  61517. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  61518. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61519. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61520. return _this;
  61521. }
  61522. RawTexture.prototype.update = function (data) {
  61523. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  61524. };
  61525. // Statics
  61526. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  61527. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61528. if (invertY === void 0) { invertY = false; }
  61529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61530. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  61531. };
  61532. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  61533. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61534. if (invertY === void 0) { invertY = false; }
  61535. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61536. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  61537. };
  61538. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  61539. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61540. if (invertY === void 0) { invertY = false; }
  61541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61542. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  61543. };
  61544. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  61545. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61546. if (invertY === void 0) { invertY = false; }
  61547. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61548. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61549. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  61550. };
  61551. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  61552. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61553. if (invertY === void 0) { invertY = false; }
  61554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61555. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61556. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  61557. };
  61558. return RawTexture;
  61559. }(BABYLON.Texture));
  61560. BABYLON.RawTexture = RawTexture;
  61561. })(BABYLON || (BABYLON = {}));
  61562. //# sourceMappingURL=babylon.rawTexture.js.map
  61563. "use strict";
  61564. var BABYLON;
  61565. (function (BABYLON) {
  61566. /**
  61567. * PostProcess can be used to apply a shader to a texture after it has been rendered
  61568. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  61569. */
  61570. var PostProcess = /** @class */ (function () {
  61571. /**
  61572. * Creates a new instance PostProcess
  61573. * @param name The name of the PostProcess.
  61574. * @param fragmentUrl The url of the fragment shader to be used.
  61575. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  61576. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  61577. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  61578. * @param camera The camera to apply the render pass to.
  61579. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  61580. * @param engine The engine which the post process will be applied. (default: current engine)
  61581. * @param reusable If the post process can be reused on the same frame. (default: false)
  61582. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  61583. * @param textureType Type of textures used when performing the post process. (default: 0)
  61584. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  61585. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  61586. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  61587. */
  61588. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  61589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  61590. if (defines === void 0) { defines = null; }
  61591. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61592. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  61593. if (blockCompilation === void 0) { blockCompilation = false; }
  61594. this.name = name;
  61595. /**
  61596. * Width of the texture to apply the post process on
  61597. */
  61598. this.width = -1;
  61599. /**
  61600. * Height of the texture to apply the post process on
  61601. */
  61602. this.height = -1;
  61603. /**
  61604. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  61605. */
  61606. this._outputTexture = null;
  61607. /**
  61608. * If the buffer needs to be cleared before applying the post process. (default: true)
  61609. * Should be set to false if shader will overwrite all previous pixels.
  61610. */
  61611. this.autoClear = true;
  61612. /**
  61613. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  61614. */
  61615. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  61616. /**
  61617. * Animations to be used for the post processing
  61618. */
  61619. this.animations = new Array();
  61620. /**
  61621. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  61622. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  61623. */
  61624. this.enablePixelPerfectMode = false;
  61625. /**
  61626. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  61627. */
  61628. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  61629. /**
  61630. * Force textures to be a power of two (default: false)
  61631. */
  61632. this.alwaysForcePOT = false;
  61633. /**
  61634. * Number of sample textures (default: 1)
  61635. */
  61636. this.samples = 1;
  61637. /**
  61638. * Modify the scale of the post process to be the same as the viewport (default: false)
  61639. */
  61640. this.adaptScaleToCurrentViewport = false;
  61641. this._reusable = false;
  61642. /**
  61643. * Smart array of input and output textures for the post process.
  61644. */
  61645. this._textures = new BABYLON.SmartArray(2);
  61646. /**
  61647. * The index in _textures that corresponds to the output texture.
  61648. */
  61649. this._currentRenderTextureInd = 0;
  61650. this._scaleRatio = new BABYLON.Vector2(1, 1);
  61651. this._texelSize = BABYLON.Vector2.Zero();
  61652. // Events
  61653. /**
  61654. * An event triggered when the postprocess is activated.
  61655. */
  61656. this.onActivateObservable = new BABYLON.Observable();
  61657. /**
  61658. * An event triggered when the postprocess changes its size.
  61659. */
  61660. this.onSizeChangedObservable = new BABYLON.Observable();
  61661. /**
  61662. * An event triggered when the postprocess applies its effect.
  61663. */
  61664. this.onApplyObservable = new BABYLON.Observable();
  61665. /**
  61666. * An event triggered before rendering the postprocess
  61667. */
  61668. this.onBeforeRenderObservable = new BABYLON.Observable();
  61669. /**
  61670. * An event triggered after rendering the postprocess
  61671. */
  61672. this.onAfterRenderObservable = new BABYLON.Observable();
  61673. if (camera != null) {
  61674. this._camera = camera;
  61675. this._scene = camera.getScene();
  61676. camera.attachPostProcess(this);
  61677. this._engine = this._scene.getEngine();
  61678. this._scene.postProcesses.push(this);
  61679. }
  61680. else if (engine) {
  61681. this._engine = engine;
  61682. this._engine.postProcesses.push(this);
  61683. }
  61684. this._options = options;
  61685. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  61686. this._reusable = reusable || false;
  61687. this._textureType = textureType;
  61688. this._samplers = samplers || [];
  61689. this._samplers.push("textureSampler");
  61690. this._fragmentUrl = fragmentUrl;
  61691. this._vertexUrl = vertexUrl;
  61692. this._parameters = parameters || [];
  61693. this._parameters.push("scale");
  61694. this._indexParameters = indexParameters;
  61695. if (!blockCompilation) {
  61696. this.updateEffect(defines);
  61697. }
  61698. }
  61699. Object.defineProperty(PostProcess.prototype, "onActivate", {
  61700. /**
  61701. * A function that is added to the onActivateObservable
  61702. */
  61703. set: function (callback) {
  61704. if (this._onActivateObserver) {
  61705. this.onActivateObservable.remove(this._onActivateObserver);
  61706. }
  61707. if (callback) {
  61708. this._onActivateObserver = this.onActivateObservable.add(callback);
  61709. }
  61710. },
  61711. enumerable: true,
  61712. configurable: true
  61713. });
  61714. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  61715. /**
  61716. * A function that is added to the onSizeChangedObservable
  61717. */
  61718. set: function (callback) {
  61719. if (this._onSizeChangedObserver) {
  61720. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  61721. }
  61722. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  61723. },
  61724. enumerable: true,
  61725. configurable: true
  61726. });
  61727. Object.defineProperty(PostProcess.prototype, "onApply", {
  61728. /**
  61729. * A function that is added to the onApplyObservable
  61730. */
  61731. set: function (callback) {
  61732. if (this._onApplyObserver) {
  61733. this.onApplyObservable.remove(this._onApplyObserver);
  61734. }
  61735. this._onApplyObserver = this.onApplyObservable.add(callback);
  61736. },
  61737. enumerable: true,
  61738. configurable: true
  61739. });
  61740. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  61741. /**
  61742. * A function that is added to the onBeforeRenderObservable
  61743. */
  61744. set: function (callback) {
  61745. if (this._onBeforeRenderObserver) {
  61746. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61747. }
  61748. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61749. },
  61750. enumerable: true,
  61751. configurable: true
  61752. });
  61753. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  61754. /**
  61755. * A function that is added to the onAfterRenderObservable
  61756. */
  61757. set: function (callback) {
  61758. if (this._onAfterRenderObserver) {
  61759. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61760. }
  61761. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61762. },
  61763. enumerable: true,
  61764. configurable: true
  61765. });
  61766. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  61767. /**
  61768. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  61769. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  61770. */
  61771. get: function () {
  61772. return this._textures.data[this._currentRenderTextureInd];
  61773. },
  61774. set: function (value) {
  61775. this._forcedOutputTexture = value;
  61776. },
  61777. enumerable: true,
  61778. configurable: true
  61779. });
  61780. /**
  61781. * Gets the camera which post process is applied to.
  61782. * @returns The camera the post process is applied to.
  61783. */
  61784. PostProcess.prototype.getCamera = function () {
  61785. return this._camera;
  61786. };
  61787. Object.defineProperty(PostProcess.prototype, "texelSize", {
  61788. /**
  61789. * Gets the texel size of the postprocess.
  61790. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  61791. */
  61792. get: function () {
  61793. if (this._shareOutputWithPostProcess) {
  61794. return this._shareOutputWithPostProcess.texelSize;
  61795. }
  61796. if (this._forcedOutputTexture) {
  61797. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  61798. }
  61799. return this._texelSize;
  61800. },
  61801. enumerable: true,
  61802. configurable: true
  61803. });
  61804. /**
  61805. * Gets the engine which this post process belongs to.
  61806. * @returns The engine the post process was enabled with.
  61807. */
  61808. PostProcess.prototype.getEngine = function () {
  61809. return this._engine;
  61810. };
  61811. /**
  61812. * The effect that is created when initializing the post process.
  61813. * @returns The created effect corrisponding the the postprocess.
  61814. */
  61815. PostProcess.prototype.getEffect = function () {
  61816. return this._effect;
  61817. };
  61818. /**
  61819. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  61820. * @param postProcess The post process to share the output with.
  61821. * @returns This post process.
  61822. */
  61823. PostProcess.prototype.shareOutputWith = function (postProcess) {
  61824. this._disposeTextures();
  61825. this._shareOutputWithPostProcess = postProcess;
  61826. return this;
  61827. };
  61828. /**
  61829. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  61830. * This should be called if the post process that shares output with this post process is disabled/disposed.
  61831. */
  61832. PostProcess.prototype.useOwnOutput = function () {
  61833. if (this._textures.length == 0) {
  61834. this._textures = new BABYLON.SmartArray(2);
  61835. }
  61836. this._shareOutputWithPostProcess = null;
  61837. };
  61838. /**
  61839. * Updates the effect with the current post process compile time values and recompiles the shader.
  61840. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  61841. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  61842. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  61843. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  61844. * @param onCompiled Called when the shader has been compiled.
  61845. * @param onError Called if there is an error when compiling a shader.
  61846. */
  61847. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  61848. if (defines === void 0) { defines = null; }
  61849. if (uniforms === void 0) { uniforms = null; }
  61850. if (samplers === void 0) { samplers = null; }
  61851. 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);
  61852. };
  61853. /**
  61854. * The post process is reusable if it can be used multiple times within one frame.
  61855. * @returns If the post process is reusable
  61856. */
  61857. PostProcess.prototype.isReusable = function () {
  61858. return this._reusable;
  61859. };
  61860. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  61861. PostProcess.prototype.markTextureDirty = function () {
  61862. this.width = -1;
  61863. };
  61864. /**
  61865. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  61866. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  61867. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  61868. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  61869. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  61870. * @returns The target texture that was bound to be written to.
  61871. */
  61872. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  61873. var _this = this;
  61874. if (sourceTexture === void 0) { sourceTexture = null; }
  61875. camera = camera || this._camera;
  61876. var scene = camera.getScene();
  61877. var engine = scene.getEngine();
  61878. var maxSize = engine.getCaps().maxTextureSize;
  61879. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  61880. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  61881. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  61882. var webVRCamera = camera.parent;
  61883. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  61884. requiredWidth /= 2;
  61885. }
  61886. var desiredWidth = (this._options.width || requiredWidth);
  61887. var desiredHeight = this._options.height || requiredHeight;
  61888. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  61889. if (this.adaptScaleToCurrentViewport) {
  61890. var currentViewport = engine.currentViewport;
  61891. if (currentViewport) {
  61892. desiredWidth *= currentViewport.width;
  61893. desiredHeight *= currentViewport.height;
  61894. }
  61895. }
  61896. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  61897. if (!this._options.width) {
  61898. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  61899. }
  61900. if (!this._options.height) {
  61901. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  61902. }
  61903. }
  61904. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  61905. if (this._textures.length > 0) {
  61906. for (var i = 0; i < this._textures.length; i++) {
  61907. this._engine._releaseTexture(this._textures.data[i]);
  61908. }
  61909. this._textures.reset();
  61910. }
  61911. this.width = desiredWidth;
  61912. this.height = desiredHeight;
  61913. var textureSize = { width: this.width, height: this.height };
  61914. var textureOptions = {
  61915. generateMipMaps: false,
  61916. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  61917. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  61918. samplingMode: this.renderTargetSamplingMode,
  61919. type: this._textureType
  61920. };
  61921. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  61922. if (this._reusable) {
  61923. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  61924. }
  61925. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  61926. this.onSizeChangedObservable.notifyObservers(this);
  61927. }
  61928. this._textures.forEach(function (texture) {
  61929. if (texture.samples !== _this.samples) {
  61930. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  61931. }
  61932. });
  61933. }
  61934. var target;
  61935. if (this._shareOutputWithPostProcess) {
  61936. target = this._shareOutputWithPostProcess.inputTexture;
  61937. }
  61938. else if (this._forcedOutputTexture) {
  61939. target = this._forcedOutputTexture;
  61940. this.width = this._forcedOutputTexture.width;
  61941. this.height = this._forcedOutputTexture.height;
  61942. }
  61943. else {
  61944. target = this.inputTexture;
  61945. }
  61946. // Bind the input of this post process to be used as the output of the previous post process.
  61947. if (this.enablePixelPerfectMode) {
  61948. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  61949. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  61950. }
  61951. else {
  61952. this._scaleRatio.copyFromFloats(1, 1);
  61953. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  61954. }
  61955. this.onActivateObservable.notifyObservers(camera);
  61956. // Clear
  61957. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  61958. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  61959. }
  61960. if (this._reusable) {
  61961. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  61962. }
  61963. return target;
  61964. };
  61965. Object.defineProperty(PostProcess.prototype, "isSupported", {
  61966. /**
  61967. * If the post process is supported.
  61968. */
  61969. get: function () {
  61970. return this._effect.isSupported;
  61971. },
  61972. enumerable: true,
  61973. configurable: true
  61974. });
  61975. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  61976. /**
  61977. * The aspect ratio of the output texture.
  61978. */
  61979. get: function () {
  61980. if (this._shareOutputWithPostProcess) {
  61981. return this._shareOutputWithPostProcess.aspectRatio;
  61982. }
  61983. if (this._forcedOutputTexture) {
  61984. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  61985. }
  61986. return this.width / this.height;
  61987. },
  61988. enumerable: true,
  61989. configurable: true
  61990. });
  61991. /**
  61992. * Get a value indicating if the post-process is ready to be used
  61993. * @returns true if the post-process is ready (shader is compiled)
  61994. */
  61995. PostProcess.prototype.isReady = function () {
  61996. return this._effect && this._effect.isReady();
  61997. };
  61998. /**
  61999. * Binds all textures and uniforms to the shader, this will be run on every pass.
  62000. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  62001. */
  62002. PostProcess.prototype.apply = function () {
  62003. // Check
  62004. if (!this._effect || !this._effect.isReady())
  62005. return null;
  62006. // States
  62007. this._engine.enableEffect(this._effect);
  62008. this._engine.setState(false);
  62009. this._engine.setDepthBuffer(false);
  62010. this._engine.setDepthWrite(false);
  62011. // Alpha
  62012. this._engine.setAlphaMode(this.alphaMode);
  62013. if (this.alphaConstants) {
  62014. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  62015. }
  62016. // Bind the output texture of the preivous post process as the input to this post process.
  62017. var source;
  62018. if (this._shareOutputWithPostProcess) {
  62019. source = this._shareOutputWithPostProcess.inputTexture;
  62020. }
  62021. else if (this._forcedOutputTexture) {
  62022. source = this._forcedOutputTexture;
  62023. }
  62024. else {
  62025. source = this.inputTexture;
  62026. }
  62027. this._effect._bindTexture("textureSampler", source);
  62028. // Parameters
  62029. this._effect.setVector2("scale", this._scaleRatio);
  62030. this.onApplyObservable.notifyObservers(this._effect);
  62031. return this._effect;
  62032. };
  62033. PostProcess.prototype._disposeTextures = function () {
  62034. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  62035. return;
  62036. }
  62037. if (this._textures.length > 0) {
  62038. for (var i = 0; i < this._textures.length; i++) {
  62039. this._engine._releaseTexture(this._textures.data[i]);
  62040. }
  62041. }
  62042. this._textures.dispose();
  62043. };
  62044. /**
  62045. * Disposes the post process.
  62046. * @param camera The camera to dispose the post process on.
  62047. */
  62048. PostProcess.prototype.dispose = function (camera) {
  62049. camera = camera || this._camera;
  62050. this._disposeTextures();
  62051. if (this._scene) {
  62052. var index_1 = this._scene.postProcesses.indexOf(this);
  62053. if (index_1 !== -1) {
  62054. this._scene.postProcesses.splice(index_1, 1);
  62055. }
  62056. }
  62057. else {
  62058. var index_2 = this._engine.postProcesses.indexOf(this);
  62059. if (index_2 !== -1) {
  62060. this._engine.postProcesses.splice(index_2, 1);
  62061. }
  62062. }
  62063. if (!camera) {
  62064. return;
  62065. }
  62066. camera.detachPostProcess(this);
  62067. var index = camera._postProcesses.indexOf(this);
  62068. if (index === 0 && camera._postProcesses.length > 0) {
  62069. var firstPostProcess = this._camera._getFirstPostProcess();
  62070. if (firstPostProcess) {
  62071. firstPostProcess.markTextureDirty();
  62072. }
  62073. }
  62074. this.onActivateObservable.clear();
  62075. this.onAfterRenderObservable.clear();
  62076. this.onApplyObservable.clear();
  62077. this.onBeforeRenderObservable.clear();
  62078. this.onSizeChangedObservable.clear();
  62079. };
  62080. return PostProcess;
  62081. }());
  62082. BABYLON.PostProcess = PostProcess;
  62083. })(BABYLON || (BABYLON = {}));
  62084. //# sourceMappingURL=babylon.postProcess.js.map
  62085. "use strict";
  62086. var BABYLON;
  62087. (function (BABYLON) {
  62088. var PassPostProcess = /** @class */ (function (_super) {
  62089. __extends(PassPostProcess, _super);
  62090. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  62091. if (camera === void 0) { camera = null; }
  62092. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62093. if (blockCompilation === void 0) { blockCompilation = false; }
  62094. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  62095. }
  62096. return PassPostProcess;
  62097. }(BABYLON.PostProcess));
  62098. BABYLON.PassPostProcess = PassPostProcess;
  62099. })(BABYLON || (BABYLON = {}));
  62100. //# sourceMappingURL=babylon.passPostProcess.js.map
  62101. "use strict";
  62102. var __assign = (this && this.__assign) || Object.assign || function(t) {
  62103. for (var s, i = 1, n = arguments.length; i < n; i++) {
  62104. s = arguments[i];
  62105. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  62106. t[p] = s[p];
  62107. }
  62108. return t;
  62109. };
  62110. var BABYLON;
  62111. (function (BABYLON) {
  62112. /**
  62113. * Default implementation IShadowGenerator.
  62114. * This is the main object responsible of generating shadows in the framework.
  62115. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  62116. */
  62117. var ShadowGenerator = /** @class */ (function () {
  62118. /**
  62119. * Creates a ShadowGenerator object.
  62120. * A ShadowGenerator is the required tool to use the shadows.
  62121. * Each light casting shadows needs to use its own ShadowGenerator.
  62122. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  62123. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  62124. * @param light The light object generating the shadows.
  62125. * @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.
  62126. */
  62127. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  62128. this._bias = 0.00005;
  62129. this._normalBias = 0;
  62130. this._blurBoxOffset = 1;
  62131. this._blurScale = 2;
  62132. this._blurKernel = 1;
  62133. this._useKernelBlur = false;
  62134. this._filter = ShadowGenerator.FILTER_NONE;
  62135. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  62136. this._contactHardeningLightSizeUVRatio = 0.1;
  62137. this._darkness = 0;
  62138. this._transparencyShadow = false;
  62139. /**
  62140. * Controls the extent to which the shadows fade out at the edge of the frustum
  62141. * Used only by directionals and spots
  62142. */
  62143. this.frustumEdgeFalloff = 0;
  62144. /**
  62145. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  62146. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  62147. * It might on the other hand introduce peter panning.
  62148. */
  62149. this.forceBackFacesOnly = false;
  62150. this._lightDirection = BABYLON.Vector3.Zero();
  62151. this._viewMatrix = BABYLON.Matrix.Zero();
  62152. this._projectionMatrix = BABYLON.Matrix.Zero();
  62153. this._transformMatrix = BABYLON.Matrix.Zero();
  62154. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  62155. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  62156. this._currentFaceIndex = 0;
  62157. this._currentFaceIndexCache = 0;
  62158. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  62159. this._mapSize = mapSize;
  62160. this._light = light;
  62161. this._scene = light.getScene();
  62162. light._shadowGenerator = this;
  62163. // Texture type fallback from float to int if not supported.
  62164. var caps = this._scene.getEngine().getCaps();
  62165. if (!useFullFloatFirst) {
  62166. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  62167. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62168. }
  62169. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  62170. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62171. }
  62172. else {
  62173. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62174. }
  62175. }
  62176. else {
  62177. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  62178. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62179. }
  62180. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  62181. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62182. }
  62183. else {
  62184. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62185. }
  62186. }
  62187. this._initializeGenerator();
  62188. this._applyFilterValues();
  62189. }
  62190. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  62191. /**
  62192. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  62193. */
  62194. get: function () {
  62195. return this._bias;
  62196. },
  62197. /**
  62198. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  62199. */
  62200. set: function (bias) {
  62201. this._bias = bias;
  62202. },
  62203. enumerable: true,
  62204. configurable: true
  62205. });
  62206. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  62207. /**
  62208. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  62209. */
  62210. get: function () {
  62211. return this._normalBias;
  62212. },
  62213. /**
  62214. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  62215. */
  62216. set: function (normalBias) {
  62217. this._normalBias = normalBias;
  62218. },
  62219. enumerable: true,
  62220. configurable: true
  62221. });
  62222. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  62223. /**
  62224. * Gets the blur box offset: offset applied during the blur pass.
  62225. * Only usefull if useKernelBlur = false
  62226. */
  62227. get: function () {
  62228. return this._blurBoxOffset;
  62229. },
  62230. /**
  62231. * Sets the blur box offset: offset applied during the blur pass.
  62232. * Only usefull if useKernelBlur = false
  62233. */
  62234. set: function (value) {
  62235. if (this._blurBoxOffset === value) {
  62236. return;
  62237. }
  62238. this._blurBoxOffset = value;
  62239. this._disposeBlurPostProcesses();
  62240. },
  62241. enumerable: true,
  62242. configurable: true
  62243. });
  62244. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  62245. /**
  62246. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  62247. * 2 means half of the size.
  62248. */
  62249. get: function () {
  62250. return this._blurScale;
  62251. },
  62252. /**
  62253. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  62254. * 2 means half of the size.
  62255. */
  62256. set: function (value) {
  62257. if (this._blurScale === value) {
  62258. return;
  62259. }
  62260. this._blurScale = value;
  62261. this._disposeBlurPostProcesses();
  62262. },
  62263. enumerable: true,
  62264. configurable: true
  62265. });
  62266. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  62267. /**
  62268. * Gets the blur kernel: kernel size of the blur pass.
  62269. * Only usefull if useKernelBlur = true
  62270. */
  62271. get: function () {
  62272. return this._blurKernel;
  62273. },
  62274. /**
  62275. * Sets the blur kernel: kernel size of the blur pass.
  62276. * Only usefull if useKernelBlur = true
  62277. */
  62278. set: function (value) {
  62279. if (this._blurKernel === value) {
  62280. return;
  62281. }
  62282. this._blurKernel = value;
  62283. this._disposeBlurPostProcesses();
  62284. },
  62285. enumerable: true,
  62286. configurable: true
  62287. });
  62288. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  62289. /**
  62290. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  62291. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  62292. */
  62293. get: function () {
  62294. return this._useKernelBlur;
  62295. },
  62296. /**
  62297. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  62298. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  62299. */
  62300. set: function (value) {
  62301. if (this._useKernelBlur === value) {
  62302. return;
  62303. }
  62304. this._useKernelBlur = value;
  62305. this._disposeBlurPostProcesses();
  62306. },
  62307. enumerable: true,
  62308. configurable: true
  62309. });
  62310. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  62311. /**
  62312. * Gets the depth scale used in ESM mode.
  62313. */
  62314. get: function () {
  62315. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  62316. },
  62317. /**
  62318. * Sets the depth scale used in ESM mode.
  62319. * This can override the scale stored on the light.
  62320. */
  62321. set: function (value) {
  62322. this._depthScale = value;
  62323. },
  62324. enumerable: true,
  62325. configurable: true
  62326. });
  62327. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  62328. /**
  62329. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  62330. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  62331. */
  62332. get: function () {
  62333. return this._filter;
  62334. },
  62335. /**
  62336. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  62337. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  62338. */
  62339. set: function (value) {
  62340. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  62341. if (this._light.needCube()) {
  62342. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  62343. this.useExponentialShadowMap = true;
  62344. return;
  62345. }
  62346. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  62347. this.useCloseExponentialShadowMap = true;
  62348. return;
  62349. }
  62350. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  62351. this.usePoissonSampling = true;
  62352. return;
  62353. }
  62354. }
  62355. // Weblg1 fallback for PCF.
  62356. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  62357. if (this._scene.getEngine().webGLVersion === 1) {
  62358. this.usePoissonSampling = true;
  62359. return;
  62360. }
  62361. }
  62362. if (this._filter === value) {
  62363. return;
  62364. }
  62365. this._filter = value;
  62366. this._disposeBlurPostProcesses();
  62367. this._applyFilterValues();
  62368. this._light._markMeshesAsLightDirty();
  62369. },
  62370. enumerable: true,
  62371. configurable: true
  62372. });
  62373. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  62374. /**
  62375. * Gets if the current filter is set to Poisson Sampling.
  62376. */
  62377. get: function () {
  62378. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  62379. },
  62380. /**
  62381. * Sets the current filter to Poisson Sampling.
  62382. */
  62383. set: function (value) {
  62384. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  62385. return;
  62386. }
  62387. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  62388. },
  62389. enumerable: true,
  62390. configurable: true
  62391. });
  62392. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  62393. /**
  62394. * Gets if the current filter is set to VSM.
  62395. * DEPRECATED. Should use useExponentialShadowMap instead.
  62396. */
  62397. get: function () {
  62398. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  62399. return this.useExponentialShadowMap;
  62400. },
  62401. /**
  62402. * Sets the current filter is to VSM.
  62403. * DEPRECATED. Should use useExponentialShadowMap instead.
  62404. */
  62405. set: function (value) {
  62406. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  62407. this.useExponentialShadowMap = value;
  62408. },
  62409. enumerable: true,
  62410. configurable: true
  62411. });
  62412. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  62413. /**
  62414. * Gets if the current filter is set to blurred VSM.
  62415. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  62416. */
  62417. get: function () {
  62418. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  62419. return this.useBlurExponentialShadowMap;
  62420. },
  62421. /**
  62422. * Sets the current filter is to blurred VSM.
  62423. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  62424. */
  62425. set: function (value) {
  62426. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  62427. this.useBlurExponentialShadowMap = value;
  62428. },
  62429. enumerable: true,
  62430. configurable: true
  62431. });
  62432. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  62433. /**
  62434. * Gets if the current filter is set to ESM.
  62435. */
  62436. get: function () {
  62437. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  62438. },
  62439. /**
  62440. * Sets the current filter is to ESM.
  62441. */
  62442. set: function (value) {
  62443. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  62444. return;
  62445. }
  62446. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  62447. },
  62448. enumerable: true,
  62449. configurable: true
  62450. });
  62451. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  62452. /**
  62453. * Gets if the current filter is set to filtered ESM.
  62454. */
  62455. get: function () {
  62456. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  62457. },
  62458. /**
  62459. * Gets if the current filter is set to filtered ESM.
  62460. */
  62461. set: function (value) {
  62462. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  62463. return;
  62464. }
  62465. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  62466. },
  62467. enumerable: true,
  62468. configurable: true
  62469. });
  62470. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  62471. /**
  62472. * Gets if the current filter is set to "close ESM" (using the inverse of the
  62473. * exponential to prevent steep falloff artifacts).
  62474. */
  62475. get: function () {
  62476. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  62477. },
  62478. /**
  62479. * Sets the current filter to "close ESM" (using the inverse of the
  62480. * exponential to prevent steep falloff artifacts).
  62481. */
  62482. set: function (value) {
  62483. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  62484. return;
  62485. }
  62486. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  62487. },
  62488. enumerable: true,
  62489. configurable: true
  62490. });
  62491. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  62492. /**
  62493. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  62494. * exponential to prevent steep falloff artifacts).
  62495. */
  62496. get: function () {
  62497. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  62498. },
  62499. /**
  62500. * Sets the current filter to filtered "close ESM" (using the inverse of the
  62501. * exponential to prevent steep falloff artifacts).
  62502. */
  62503. set: function (value) {
  62504. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  62505. return;
  62506. }
  62507. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  62508. },
  62509. enumerable: true,
  62510. configurable: true
  62511. });
  62512. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  62513. /**
  62514. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  62515. */
  62516. get: function () {
  62517. return this.filter === ShadowGenerator.FILTER_PCF;
  62518. },
  62519. /**
  62520. * Sets the current filter to "PCF" (percentage closer filtering).
  62521. */
  62522. set: function (value) {
  62523. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  62524. return;
  62525. }
  62526. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  62527. },
  62528. enumerable: true,
  62529. configurable: true
  62530. });
  62531. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  62532. /**
  62533. * Gets the PCF or PCSS Quality.
  62534. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  62535. */
  62536. get: function () {
  62537. return this._filteringQuality;
  62538. },
  62539. /**
  62540. * Sets the PCF or PCSS Quality.
  62541. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  62542. */
  62543. set: function (filteringQuality) {
  62544. this._filteringQuality = filteringQuality;
  62545. },
  62546. enumerable: true,
  62547. configurable: true
  62548. });
  62549. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  62550. /**
  62551. * Gets if the current filter is set to "PCSS" (contact hardening).
  62552. */
  62553. get: function () {
  62554. return this.filter === ShadowGenerator.FILTER_PCSS;
  62555. },
  62556. /**
  62557. * Sets the current filter to "PCSS" (contact hardening).
  62558. */
  62559. set: function (value) {
  62560. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  62561. return;
  62562. }
  62563. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  62564. },
  62565. enumerable: true,
  62566. configurable: true
  62567. });
  62568. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  62569. /**
  62570. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  62571. * Using a ratio helps keeping shape stability independently of the map size.
  62572. *
  62573. * It does not account for the light projection as it was having too much
  62574. * instability during the light setup or during light position changes.
  62575. *
  62576. * Only valid if useContactHardeningShadow is true.
  62577. */
  62578. get: function () {
  62579. return this._contactHardeningLightSizeUVRatio;
  62580. },
  62581. /**
  62582. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  62583. * Using a ratio helps keeping shape stability independently of the map size.
  62584. *
  62585. * It does not account for the light projection as it was having too much
  62586. * instability during the light setup or during light position changes.
  62587. *
  62588. * Only valid if useContactHardeningShadow is true.
  62589. */
  62590. set: function (contactHardeningLightSizeUVRatio) {
  62591. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  62592. },
  62593. enumerable: true,
  62594. configurable: true
  62595. });
  62596. /**
  62597. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  62598. * 0 means strongest and 1 would means no shadow.
  62599. * @returns the darkness.
  62600. */
  62601. ShadowGenerator.prototype.getDarkness = function () {
  62602. return this._darkness;
  62603. };
  62604. /**
  62605. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  62606. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  62607. * @returns the shadow generator allowing fluent coding.
  62608. */
  62609. ShadowGenerator.prototype.setDarkness = function (darkness) {
  62610. if (darkness >= 1.0)
  62611. this._darkness = 1.0;
  62612. else if (darkness <= 0.0)
  62613. this._darkness = 0.0;
  62614. else
  62615. this._darkness = darkness;
  62616. return this;
  62617. };
  62618. /**
  62619. * Sets the ability to have transparent shadow (boolean).
  62620. * @param transparent True if transparent else False
  62621. * @returns the shadow generator allowing fluent coding
  62622. */
  62623. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  62624. this._transparencyShadow = transparent;
  62625. return this;
  62626. };
  62627. /**
  62628. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  62629. * @returns The render target texture if present otherwise, null
  62630. */
  62631. ShadowGenerator.prototype.getShadowMap = function () {
  62632. return this._shadowMap;
  62633. };
  62634. /**
  62635. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  62636. * @returns The render target texture if the shadow map is present otherwise, null
  62637. */
  62638. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  62639. if (this._shadowMap2) {
  62640. return this._shadowMap2;
  62641. }
  62642. return this._shadowMap;
  62643. };
  62644. /**
  62645. * Helper function to add a mesh and its descendants to the list of shadow casters.
  62646. * @param mesh Mesh to add
  62647. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  62648. * @returns the Shadow Generator itself
  62649. */
  62650. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  62651. if (includeDescendants === void 0) { includeDescendants = true; }
  62652. if (!this._shadowMap) {
  62653. return this;
  62654. }
  62655. if (!this._shadowMap.renderList) {
  62656. this._shadowMap.renderList = [];
  62657. }
  62658. this._shadowMap.renderList.push(mesh);
  62659. if (includeDescendants) {
  62660. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  62661. }
  62662. return this;
  62663. var _a;
  62664. };
  62665. /**
  62666. * Helper function to remove a mesh and its descendants from the list of shadow casters
  62667. * @param mesh Mesh to remove
  62668. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  62669. * @returns the Shadow Generator itself
  62670. */
  62671. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  62672. if (includeDescendants === void 0) { includeDescendants = true; }
  62673. if (!this._shadowMap || !this._shadowMap.renderList) {
  62674. return this;
  62675. }
  62676. var index = this._shadowMap.renderList.indexOf(mesh);
  62677. if (index !== -1) {
  62678. this._shadowMap.renderList.splice(index, 1);
  62679. }
  62680. if (includeDescendants) {
  62681. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  62682. var child = _a[_i];
  62683. this.removeShadowCaster(child);
  62684. }
  62685. }
  62686. return this;
  62687. };
  62688. /**
  62689. * Returns the associated light object.
  62690. * @returns the light generating the shadow
  62691. */
  62692. ShadowGenerator.prototype.getLight = function () {
  62693. return this._light;
  62694. };
  62695. ShadowGenerator.prototype._initializeGenerator = function () {
  62696. this._light._markMeshesAsLightDirty();
  62697. this._initializeShadowMap();
  62698. };
  62699. ShadowGenerator.prototype._initializeShadowMap = function () {
  62700. var _this = this;
  62701. // Render target
  62702. var engine = this._scene.getEngine();
  62703. if (engine.webGLVersion > 1) {
  62704. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  62705. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  62706. }
  62707. else {
  62708. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  62709. }
  62710. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62711. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62712. this._shadowMap.anisotropicFilteringLevel = 1;
  62713. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62714. this._shadowMap.renderParticles = false;
  62715. this._shadowMap.ignoreCameraViewport = true;
  62716. // Record Face Index before render.
  62717. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  62718. _this._currentFaceIndex = faceIndex;
  62719. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  62720. engine.setColorWrite(false);
  62721. }
  62722. });
  62723. // Custom render function.
  62724. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  62725. // Blur if required afer render.
  62726. this._shadowMap.onAfterUnbindObservable.add(function () {
  62727. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  62728. engine.setColorWrite(true);
  62729. }
  62730. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  62731. return;
  62732. }
  62733. var shadowMap = _this.getShadowMapForRendering();
  62734. if (shadowMap) {
  62735. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  62736. }
  62737. });
  62738. // Clear according to the chosen filter.
  62739. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  62740. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62741. this._shadowMap.onClearObservable.add(function (engine) {
  62742. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  62743. engine.clear(clearOne, false, true, false);
  62744. }
  62745. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  62746. engine.clear(clearZero, true, true, false);
  62747. }
  62748. else {
  62749. engine.clear(clearOne, true, true, false);
  62750. }
  62751. });
  62752. };
  62753. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  62754. var _this = this;
  62755. var engine = this._scene.getEngine();
  62756. var targetSize = this._mapSize / this.blurScale;
  62757. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  62758. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  62759. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62760. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62761. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62762. }
  62763. if (this.useKernelBlur) {
  62764. 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);
  62765. this._kernelBlurXPostprocess.width = targetSize;
  62766. this._kernelBlurXPostprocess.height = targetSize;
  62767. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  62768. effect.setTexture("textureSampler", _this._shadowMap);
  62769. });
  62770. 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);
  62771. this._kernelBlurXPostprocess.autoClear = false;
  62772. this._kernelBlurYPostprocess.autoClear = false;
  62773. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62774. this._kernelBlurXPostprocess.packedFloat = true;
  62775. this._kernelBlurYPostprocess.packedFloat = true;
  62776. }
  62777. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  62778. }
  62779. else {
  62780. 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);
  62781. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  62782. effect.setFloat2("screenSize", targetSize, targetSize);
  62783. effect.setTexture("textureSampler", _this._shadowMap);
  62784. });
  62785. this._boxBlurPostprocess.autoClear = false;
  62786. this._blurPostProcesses = [this._boxBlurPostprocess];
  62787. }
  62788. };
  62789. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62790. var index;
  62791. var engine = this._scene.getEngine();
  62792. if (depthOnlySubMeshes.length) {
  62793. engine.setColorWrite(false);
  62794. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62795. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  62796. }
  62797. engine.setColorWrite(true);
  62798. }
  62799. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62800. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  62801. }
  62802. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62803. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  62804. }
  62805. if (this._transparencyShadow) {
  62806. for (index = 0; index < transparentSubMeshes.length; index++) {
  62807. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  62808. }
  62809. }
  62810. };
  62811. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  62812. var _this = this;
  62813. var mesh = subMesh.getRenderingMesh();
  62814. var scene = this._scene;
  62815. var engine = scene.getEngine();
  62816. var material = subMesh.getMaterial();
  62817. if (!material) {
  62818. return;
  62819. }
  62820. // Culling
  62821. engine.setState(material.backFaceCulling);
  62822. // Managing instances
  62823. var batch = mesh._getInstancesRenderList(subMesh._id);
  62824. if (batch.mustReturn) {
  62825. return;
  62826. }
  62827. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  62828. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  62829. engine.enableEffect(this._effect);
  62830. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  62831. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  62832. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  62833. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62834. this._effect.setVector3("lightData", this._cachedDirection);
  62835. }
  62836. else {
  62837. this._effect.setVector3("lightData", this._cachedPosition);
  62838. }
  62839. if (scene.activeCamera) {
  62840. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  62841. }
  62842. // Alpha test
  62843. if (material && material.needAlphaTesting()) {
  62844. var alphaTexture = material.getAlphaTestTexture();
  62845. if (alphaTexture) {
  62846. this._effect.setTexture("diffuseSampler", alphaTexture);
  62847. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  62848. }
  62849. }
  62850. // Bones
  62851. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62852. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  62853. }
  62854. // Morph targets
  62855. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  62856. if (this.forceBackFacesOnly) {
  62857. engine.setState(true, 0, false, true);
  62858. }
  62859. // Draw
  62860. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62861. if (this.forceBackFacesOnly) {
  62862. engine.setState(true, 0, false, false);
  62863. }
  62864. }
  62865. else {
  62866. // Need to reset refresh rate of the shadowMap
  62867. if (this._shadowMap) {
  62868. this._shadowMap.resetRefreshCounter();
  62869. }
  62870. }
  62871. };
  62872. ShadowGenerator.prototype._applyFilterValues = function () {
  62873. if (!this._shadowMap) {
  62874. return;
  62875. }
  62876. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  62877. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62878. }
  62879. else {
  62880. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62881. }
  62882. };
  62883. /**
  62884. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  62885. * @param onCompiled Callback triggered at the and of the effects compilation
  62886. * @param options Sets of optional options forcing the compilation with different modes
  62887. */
  62888. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  62889. var _this = this;
  62890. var localOptions = __assign({ useInstances: false }, options);
  62891. var shadowMap = this.getShadowMap();
  62892. if (!shadowMap) {
  62893. if (onCompiled) {
  62894. onCompiled(this);
  62895. }
  62896. return;
  62897. }
  62898. var renderList = shadowMap.renderList;
  62899. if (!renderList) {
  62900. if (onCompiled) {
  62901. onCompiled(this);
  62902. }
  62903. return;
  62904. }
  62905. var subMeshes = new Array();
  62906. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  62907. var mesh = renderList_1[_i];
  62908. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  62909. }
  62910. if (subMeshes.length === 0) {
  62911. if (onCompiled) {
  62912. onCompiled(this);
  62913. }
  62914. return;
  62915. }
  62916. var currentIndex = 0;
  62917. var checkReady = function () {
  62918. if (!_this._scene || !_this._scene.getEngine()) {
  62919. return;
  62920. }
  62921. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  62922. currentIndex++;
  62923. if (currentIndex >= subMeshes.length) {
  62924. if (onCompiled) {
  62925. onCompiled(_this);
  62926. }
  62927. return;
  62928. }
  62929. }
  62930. setTimeout(checkReady, 16);
  62931. };
  62932. checkReady();
  62933. };
  62934. /**
  62935. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  62936. * @param options Sets of optional options forcing the compilation with different modes
  62937. * @returns A promise that resolves when the compilation completes
  62938. */
  62939. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  62940. var _this = this;
  62941. return new Promise(function (resolve) {
  62942. _this.forceCompilation(function () {
  62943. resolve();
  62944. }, options);
  62945. });
  62946. };
  62947. /**
  62948. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  62949. * @param subMesh The submesh we want to render in the shadow map
  62950. * @param useInstances Defines wether will draw in the map using instances
  62951. * @returns true if ready otherwise, false
  62952. */
  62953. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  62954. var defines = [];
  62955. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62956. defines.push("#define FLOAT");
  62957. }
  62958. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62959. defines.push("#define ESM");
  62960. }
  62961. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  62962. defines.push("#define DEPTHTEXTURE");
  62963. }
  62964. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62965. var mesh = subMesh.getMesh();
  62966. var material = subMesh.getMaterial();
  62967. // Normal bias.
  62968. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62969. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62970. defines.push("#define NORMAL");
  62971. if (mesh.nonUniformScaling) {
  62972. defines.push("#define NONUNIFORMSCALING");
  62973. }
  62974. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62975. defines.push("#define DIRECTIONINLIGHTDATA");
  62976. }
  62977. }
  62978. // Alpha test
  62979. if (material && material.needAlphaTesting()) {
  62980. var alphaTexture = material.getAlphaTestTexture();
  62981. if (alphaTexture) {
  62982. defines.push("#define ALPHATEST");
  62983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62984. attribs.push(BABYLON.VertexBuffer.UVKind);
  62985. defines.push("#define UV1");
  62986. }
  62987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62988. if (alphaTexture.coordinatesIndex === 1) {
  62989. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62990. defines.push("#define UV2");
  62991. }
  62992. }
  62993. }
  62994. }
  62995. // Bones
  62996. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62997. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62998. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62999. if (mesh.numBoneInfluencers > 4) {
  63000. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63001. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63002. }
  63003. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63004. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  63005. }
  63006. else {
  63007. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63008. }
  63009. // Morph targets
  63010. var manager = mesh.morphTargetManager;
  63011. var morphInfluencers = 0;
  63012. if (manager) {
  63013. if (manager.numInfluencers > 0) {
  63014. defines.push("#define MORPHTARGETS");
  63015. morphInfluencers = manager.numInfluencers;
  63016. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  63017. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  63018. }
  63019. }
  63020. // Instances
  63021. if (useInstances) {
  63022. defines.push("#define INSTANCES");
  63023. attribs.push("world0");
  63024. attribs.push("world1");
  63025. attribs.push("world2");
  63026. attribs.push("world3");
  63027. }
  63028. // Get correct effect
  63029. var join = defines.join("\n");
  63030. if (this._cachedDefines !== join) {
  63031. this._cachedDefines = join;
  63032. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  63033. }
  63034. if (!this._effect.isReady()) {
  63035. return false;
  63036. }
  63037. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  63038. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  63039. this._initializeBlurRTTAndPostProcesses();
  63040. }
  63041. }
  63042. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  63043. return false;
  63044. }
  63045. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  63046. return false;
  63047. }
  63048. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  63049. return false;
  63050. }
  63051. return true;
  63052. };
  63053. /**
  63054. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  63055. * @param defines Defines of the material we want to update
  63056. * @param lightIndex Index of the light in the enabled light list of the material
  63057. */
  63058. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  63059. var scene = this._scene;
  63060. var light = this._light;
  63061. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  63062. return;
  63063. }
  63064. defines["SHADOW" + lightIndex] = true;
  63065. if (this.useContactHardeningShadow) {
  63066. defines["SHADOWPCSS" + lightIndex] = true;
  63067. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  63068. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  63069. }
  63070. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  63071. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  63072. }
  63073. // else default to high.
  63074. }
  63075. if (this.usePercentageCloserFiltering) {
  63076. defines["SHADOWPCF" + lightIndex] = true;
  63077. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  63078. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  63079. }
  63080. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  63081. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  63082. }
  63083. // else default to high.
  63084. }
  63085. else if (this.usePoissonSampling) {
  63086. defines["SHADOWPOISSON" + lightIndex] = true;
  63087. }
  63088. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  63089. defines["SHADOWESM" + lightIndex] = true;
  63090. }
  63091. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  63092. defines["SHADOWCLOSEESM" + lightIndex] = true;
  63093. }
  63094. if (light.needCube()) {
  63095. defines["SHADOWCUBE" + lightIndex] = true;
  63096. }
  63097. };
  63098. /**
  63099. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  63100. * defined in the generator but impacting the effect).
  63101. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  63102. * @param effect The effect we are binfing the information for
  63103. */
  63104. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  63105. var light = this._light;
  63106. var scene = this._scene;
  63107. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  63108. return;
  63109. }
  63110. var camera = scene.activeCamera;
  63111. if (!camera) {
  63112. return;
  63113. }
  63114. var shadowMap = this.getShadowMap();
  63115. if (!shadowMap) {
  63116. return;
  63117. }
  63118. if (!light.needCube()) {
  63119. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  63120. }
  63121. // Only PCF uses depth stencil texture.
  63122. if (this._filter === ShadowGenerator.FILTER_PCF) {
  63123. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  63124. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  63125. }
  63126. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  63127. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  63128. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  63129. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  63130. }
  63131. else {
  63132. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  63133. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  63134. }
  63135. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  63136. };
  63137. /**
  63138. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  63139. * (eq to shadow prjection matrix * light transform matrix)
  63140. * @returns The transform matrix used to create the shadow map
  63141. */
  63142. ShadowGenerator.prototype.getTransformMatrix = function () {
  63143. var scene = this._scene;
  63144. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  63145. return this._transformMatrix;
  63146. }
  63147. this._currentRenderID = scene.getRenderId();
  63148. this._currentFaceIndexCache = this._currentFaceIndex;
  63149. var lightPosition = this._light.position;
  63150. if (this._light.computeTransformedInformation()) {
  63151. lightPosition = this._light.transformedPosition;
  63152. }
  63153. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  63154. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  63155. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  63156. }
  63157. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  63158. this._cachedPosition.copyFrom(lightPosition);
  63159. this._cachedDirection.copyFrom(this._lightDirection);
  63160. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  63161. var shadowMap = this.getShadowMap();
  63162. if (shadowMap) {
  63163. var renderList = shadowMap.renderList;
  63164. if (renderList) {
  63165. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  63166. }
  63167. }
  63168. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  63169. }
  63170. return this._transformMatrix;
  63171. };
  63172. /**
  63173. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  63174. * Cube and 2D textures for instance.
  63175. */
  63176. ShadowGenerator.prototype.recreateShadowMap = function () {
  63177. var shadowMap = this._shadowMap;
  63178. if (!shadowMap) {
  63179. return;
  63180. }
  63181. // Track render list.
  63182. var renderList = shadowMap.renderList;
  63183. // Clean up existing data.
  63184. this._disposeRTTandPostProcesses();
  63185. // Reinitializes.
  63186. this._initializeGenerator();
  63187. // Reaffect the filter to ensure a correct fallback if necessary.
  63188. this.filter = this.filter;
  63189. // Reaffect the filter.
  63190. this._applyFilterValues();
  63191. // Reaffect Render List.
  63192. this._shadowMap.renderList = renderList;
  63193. };
  63194. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  63195. if (this._shadowMap2) {
  63196. this._shadowMap2.dispose();
  63197. this._shadowMap2 = null;
  63198. }
  63199. if (this._boxBlurPostprocess) {
  63200. this._boxBlurPostprocess.dispose();
  63201. this._boxBlurPostprocess = null;
  63202. }
  63203. if (this._kernelBlurXPostprocess) {
  63204. this._kernelBlurXPostprocess.dispose();
  63205. this._kernelBlurXPostprocess = null;
  63206. }
  63207. if (this._kernelBlurYPostprocess) {
  63208. this._kernelBlurYPostprocess.dispose();
  63209. this._kernelBlurYPostprocess = null;
  63210. }
  63211. this._blurPostProcesses = [];
  63212. };
  63213. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  63214. if (this._shadowMap) {
  63215. this._shadowMap.dispose();
  63216. this._shadowMap = null;
  63217. }
  63218. this._disposeBlurPostProcesses();
  63219. };
  63220. /**
  63221. * Disposes the ShadowGenerator.
  63222. * Returns nothing.
  63223. */
  63224. ShadowGenerator.prototype.dispose = function () {
  63225. this._disposeRTTandPostProcesses();
  63226. if (this._light) {
  63227. this._light._shadowGenerator = null;
  63228. this._light._markMeshesAsLightDirty();
  63229. }
  63230. };
  63231. /**
  63232. * Serializes the shadow generator setup to a json object.
  63233. * @returns The serialized JSON object
  63234. */
  63235. ShadowGenerator.prototype.serialize = function () {
  63236. var serializationObject = {};
  63237. var shadowMap = this.getShadowMap();
  63238. if (!shadowMap) {
  63239. return serializationObject;
  63240. }
  63241. serializationObject.lightId = this._light.id;
  63242. serializationObject.mapSize = shadowMap.getRenderSize();
  63243. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  63244. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  63245. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  63246. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  63247. serializationObject.usePoissonSampling = this.usePoissonSampling;
  63248. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  63249. serializationObject.depthScale = this.depthScale;
  63250. serializationObject.darkness = this.getDarkness();
  63251. serializationObject.blurBoxOffset = this.blurBoxOffset;
  63252. serializationObject.blurKernel = this.blurKernel;
  63253. serializationObject.blurScale = this.blurScale;
  63254. serializationObject.useKernelBlur = this.useKernelBlur;
  63255. serializationObject.transparencyShadow = this._transparencyShadow;
  63256. serializationObject.bias = this.bias;
  63257. serializationObject.normalBias = this.normalBias;
  63258. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  63259. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  63260. serializationObject.filteringQuality = this.filteringQuality;
  63261. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  63262. serializationObject.renderList = [];
  63263. if (shadowMap.renderList) {
  63264. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  63265. var mesh = shadowMap.renderList[meshIndex];
  63266. serializationObject.renderList.push(mesh.id);
  63267. }
  63268. }
  63269. return serializationObject;
  63270. };
  63271. /**
  63272. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  63273. * @param parsedShadowGenerator The JSON object to parse
  63274. * @param scene The scene to create the shadow map for
  63275. * @returns The parsed shadow generator
  63276. */
  63277. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  63278. //casting to point light, as light is missing the position attr and typescript complains.
  63279. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  63280. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  63281. var shadowMap = shadowGenerator.getShadowMap();
  63282. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  63283. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  63284. meshes.forEach(function (mesh) {
  63285. if (!shadowMap) {
  63286. return;
  63287. }
  63288. if (!shadowMap.renderList) {
  63289. shadowMap.renderList = [];
  63290. }
  63291. shadowMap.renderList.push(mesh);
  63292. });
  63293. }
  63294. if (parsedShadowGenerator.usePoissonSampling) {
  63295. shadowGenerator.usePoissonSampling = true;
  63296. }
  63297. else if (parsedShadowGenerator.useExponentialShadowMap) {
  63298. shadowGenerator.useExponentialShadowMap = true;
  63299. }
  63300. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  63301. shadowGenerator.useBlurExponentialShadowMap = true;
  63302. }
  63303. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  63304. shadowGenerator.useCloseExponentialShadowMap = true;
  63305. }
  63306. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  63307. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  63308. }
  63309. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  63310. shadowGenerator.usePercentageCloserFiltering = true;
  63311. }
  63312. else if (parsedShadowGenerator.useContactHardeningShadow) {
  63313. shadowGenerator.useContactHardeningShadow = true;
  63314. }
  63315. if (parsedShadowGenerator.filteringQuality) {
  63316. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  63317. }
  63318. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  63319. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  63320. }
  63321. else if (parsedShadowGenerator.useVarianceShadowMap) {
  63322. shadowGenerator.useExponentialShadowMap = true;
  63323. }
  63324. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  63325. shadowGenerator.useBlurExponentialShadowMap = true;
  63326. }
  63327. if (parsedShadowGenerator.depthScale) {
  63328. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  63329. }
  63330. if (parsedShadowGenerator.blurScale) {
  63331. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  63332. }
  63333. if (parsedShadowGenerator.blurBoxOffset) {
  63334. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  63335. }
  63336. if (parsedShadowGenerator.useKernelBlur) {
  63337. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  63338. }
  63339. if (parsedShadowGenerator.blurKernel) {
  63340. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  63341. }
  63342. if (parsedShadowGenerator.bias !== undefined) {
  63343. shadowGenerator.bias = parsedShadowGenerator.bias;
  63344. }
  63345. if (parsedShadowGenerator.normalBias !== undefined) {
  63346. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  63347. }
  63348. if (parsedShadowGenerator.darkness) {
  63349. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  63350. }
  63351. if (parsedShadowGenerator.transparencyShadow) {
  63352. shadowGenerator.setTransparencyShadow(true);
  63353. }
  63354. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  63355. return shadowGenerator;
  63356. };
  63357. /**
  63358. * Shadow generator mode None: no filtering applied.
  63359. */
  63360. ShadowGenerator.FILTER_NONE = 0;
  63361. /**
  63362. * Shadow generator mode ESM: Exponential Shadow Mapping.
  63363. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  63364. */
  63365. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  63366. /**
  63367. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  63368. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  63369. */
  63370. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  63371. /**
  63372. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  63373. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  63374. */
  63375. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  63376. /**
  63377. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  63378. * edge artifacts on steep falloff.
  63379. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  63380. */
  63381. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  63382. /**
  63383. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  63384. * edge artifacts on steep falloff.
  63385. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  63386. */
  63387. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  63388. /**
  63389. * Shadow generator mode PCF: Percentage Closer Filtering
  63390. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  63391. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  63392. */
  63393. ShadowGenerator.FILTER_PCF = 6;
  63394. /**
  63395. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  63396. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  63397. * Contact Hardening
  63398. */
  63399. ShadowGenerator.FILTER_PCSS = 7;
  63400. /**
  63401. * Reserved for PCF and PCSS
  63402. * Highest Quality.
  63403. *
  63404. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  63405. *
  63406. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  63407. */
  63408. ShadowGenerator.QUALITY_HIGH = 0;
  63409. /**
  63410. * Reserved for PCF and PCSS
  63411. * Good tradeoff for quality/perf cross devices
  63412. *
  63413. * Execute PCF on a 3*3 kernel.
  63414. *
  63415. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  63416. */
  63417. ShadowGenerator.QUALITY_MEDIUM = 1;
  63418. /**
  63419. * Reserved for PCF and PCSS
  63420. * The lowest quality but the fastest.
  63421. *
  63422. * Execute PCF on a 1*1 kernel.
  63423. *
  63424. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  63425. */
  63426. ShadowGenerator.QUALITY_LOW = 2;
  63427. return ShadowGenerator;
  63428. }());
  63429. BABYLON.ShadowGenerator = ShadowGenerator;
  63430. })(BABYLON || (BABYLON = {}));
  63431. //# sourceMappingURL=babylon.shadowGenerator.js.map
  63432. "use strict";
  63433. var BABYLON;
  63434. (function (BABYLON) {
  63435. var DefaultLoadingScreen = /** @class */ (function () {
  63436. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  63437. if (_loadingText === void 0) { _loadingText = ""; }
  63438. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  63439. var _this = this;
  63440. this._renderingCanvas = _renderingCanvas;
  63441. this._loadingText = _loadingText;
  63442. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  63443. // Resize
  63444. this._resizeLoadingUI = function () {
  63445. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  63446. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  63447. if (!_this._loadingDiv) {
  63448. return;
  63449. }
  63450. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  63451. _this._loadingDiv.style.left = canvasRect.left + "px";
  63452. _this._loadingDiv.style.top = canvasRect.top + "px";
  63453. _this._loadingDiv.style.width = canvasRect.width + "px";
  63454. _this._loadingDiv.style.height = canvasRect.height + "px";
  63455. };
  63456. }
  63457. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  63458. if (this._loadingDiv) {
  63459. // Do not add a loading screen if there is already one
  63460. return;
  63461. }
  63462. this._loadingDiv = document.createElement("div");
  63463. this._loadingDiv.id = "babylonjsLoadingDiv";
  63464. this._loadingDiv.style.opacity = "0";
  63465. this._loadingDiv.style.transition = "opacity 1.5s ease";
  63466. this._loadingDiv.style.pointerEvents = "none";
  63467. // Loading text
  63468. this._loadingTextDiv = document.createElement("div");
  63469. this._loadingTextDiv.style.position = "absolute";
  63470. this._loadingTextDiv.style.left = "0";
  63471. this._loadingTextDiv.style.top = "50%";
  63472. this._loadingTextDiv.style.marginTop = "80px";
  63473. this._loadingTextDiv.style.width = "100%";
  63474. this._loadingTextDiv.style.height = "20px";
  63475. this._loadingTextDiv.style.fontFamily = "Arial";
  63476. this._loadingTextDiv.style.fontSize = "14px";
  63477. this._loadingTextDiv.style.color = "white";
  63478. this._loadingTextDiv.style.textAlign = "center";
  63479. this._loadingTextDiv.innerHTML = "Loading";
  63480. this._loadingDiv.appendChild(this._loadingTextDiv);
  63481. //set the predefined text
  63482. this._loadingTextDiv.innerHTML = this._loadingText;
  63483. // Generating keyframes
  63484. var style = document.createElement('style');
  63485. style.type = 'text/css';
  63486. 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 }";
  63487. style.innerHTML = keyFrames;
  63488. document.getElementsByTagName('head')[0].appendChild(style);
  63489. // Loading img
  63490. var imgBack = new Image();
  63491. 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";
  63492. imgBack.style.position = "absolute";
  63493. imgBack.style.left = "50%";
  63494. imgBack.style.top = "50%";
  63495. imgBack.style.marginLeft = "-60px";
  63496. imgBack.style.marginTop = "-60px";
  63497. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  63498. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  63499. imgBack.style.transformOrigin = "50% 50%";
  63500. imgBack.style.webkitTransformOrigin = "50% 50%";
  63501. this._loadingDiv.appendChild(imgBack);
  63502. this._resizeLoadingUI();
  63503. window.addEventListener("resize", this._resizeLoadingUI);
  63504. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  63505. document.body.appendChild(this._loadingDiv);
  63506. this._loadingDiv.style.opacity = "1";
  63507. };
  63508. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  63509. var _this = this;
  63510. if (!this._loadingDiv) {
  63511. return;
  63512. }
  63513. var onTransitionEnd = function () {
  63514. if (!_this._loadingDiv) {
  63515. return;
  63516. }
  63517. document.body.removeChild(_this._loadingDiv);
  63518. window.removeEventListener("resize", _this._resizeLoadingUI);
  63519. _this._loadingDiv = null;
  63520. };
  63521. this._loadingDiv.style.opacity = "0";
  63522. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  63523. };
  63524. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  63525. set: function (text) {
  63526. this._loadingText = text;
  63527. if (this._loadingTextDiv) {
  63528. this._loadingTextDiv.innerHTML = this._loadingText;
  63529. }
  63530. },
  63531. enumerable: true,
  63532. configurable: true
  63533. });
  63534. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  63535. get: function () {
  63536. return this._loadingDivBackgroundColor;
  63537. },
  63538. set: function (color) {
  63539. this._loadingDivBackgroundColor = color;
  63540. if (!this._loadingDiv) {
  63541. return;
  63542. }
  63543. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  63544. },
  63545. enumerable: true,
  63546. configurable: true
  63547. });
  63548. return DefaultLoadingScreen;
  63549. }());
  63550. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  63551. })(BABYLON || (BABYLON = {}));
  63552. //# sourceMappingURL=babylon.loadingScreen.js.map
  63553. "use strict";
  63554. var BABYLON;
  63555. (function (BABYLON) {
  63556. var SceneLoaderProgressEvent = /** @class */ (function () {
  63557. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  63558. this.lengthComputable = lengthComputable;
  63559. this.loaded = loaded;
  63560. this.total = total;
  63561. }
  63562. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  63563. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  63564. };
  63565. return SceneLoaderProgressEvent;
  63566. }());
  63567. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  63568. var SceneLoader = /** @class */ (function () {
  63569. function SceneLoader() {
  63570. }
  63571. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  63572. get: function () {
  63573. return 0;
  63574. },
  63575. enumerable: true,
  63576. configurable: true
  63577. });
  63578. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  63579. get: function () {
  63580. return 1;
  63581. },
  63582. enumerable: true,
  63583. configurable: true
  63584. });
  63585. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  63586. get: function () {
  63587. return 2;
  63588. },
  63589. enumerable: true,
  63590. configurable: true
  63591. });
  63592. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  63593. get: function () {
  63594. return 3;
  63595. },
  63596. enumerable: true,
  63597. configurable: true
  63598. });
  63599. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  63600. get: function () {
  63601. return SceneLoader._ForceFullSceneLoadingForIncremental;
  63602. },
  63603. set: function (value) {
  63604. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  63605. },
  63606. enumerable: true,
  63607. configurable: true
  63608. });
  63609. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  63610. get: function () {
  63611. return SceneLoader._ShowLoadingScreen;
  63612. },
  63613. set: function (value) {
  63614. SceneLoader._ShowLoadingScreen = value;
  63615. },
  63616. enumerable: true,
  63617. configurable: true
  63618. });
  63619. Object.defineProperty(SceneLoader, "loggingLevel", {
  63620. get: function () {
  63621. return SceneLoader._loggingLevel;
  63622. },
  63623. set: function (value) {
  63624. SceneLoader._loggingLevel = value;
  63625. },
  63626. enumerable: true,
  63627. configurable: true
  63628. });
  63629. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  63630. get: function () {
  63631. return SceneLoader._CleanBoneMatrixWeights;
  63632. },
  63633. set: function (value) {
  63634. SceneLoader._CleanBoneMatrixWeights = value;
  63635. },
  63636. enumerable: true,
  63637. configurable: true
  63638. });
  63639. SceneLoader._getDefaultPlugin = function () {
  63640. return SceneLoader._registeredPlugins[".babylon"];
  63641. };
  63642. SceneLoader._getPluginForExtension = function (extension) {
  63643. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  63644. if (registeredPlugin) {
  63645. return registeredPlugin;
  63646. }
  63647. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  63648. return SceneLoader._getDefaultPlugin();
  63649. };
  63650. SceneLoader._getPluginForDirectLoad = function (data) {
  63651. for (var extension in SceneLoader._registeredPlugins) {
  63652. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  63653. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  63654. return SceneLoader._registeredPlugins[extension];
  63655. }
  63656. }
  63657. return SceneLoader._getDefaultPlugin();
  63658. };
  63659. SceneLoader._getPluginForFilename = function (sceneFilename) {
  63660. if (sceneFilename.name) {
  63661. sceneFilename = sceneFilename.name;
  63662. }
  63663. var queryStringPosition = sceneFilename.indexOf("?");
  63664. if (queryStringPosition !== -1) {
  63665. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  63666. }
  63667. var dotPosition = sceneFilename.lastIndexOf(".");
  63668. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  63669. return SceneLoader._getPluginForExtension(extension);
  63670. };
  63671. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  63672. SceneLoader._getDirectLoad = function (sceneFilename) {
  63673. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  63674. return sceneFilename.substr(5);
  63675. }
  63676. return null;
  63677. };
  63678. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  63679. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  63680. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  63681. var plugin;
  63682. if (registeredPlugin.plugin.createPlugin) {
  63683. plugin = registeredPlugin.plugin.createPlugin();
  63684. }
  63685. else {
  63686. plugin = registeredPlugin.plugin;
  63687. }
  63688. var useArrayBuffer = registeredPlugin.isBinary;
  63689. var database;
  63690. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  63691. var dataCallback = function (data, responseURL) {
  63692. if (scene.isDisposed) {
  63693. onError("Scene has been disposed");
  63694. return;
  63695. }
  63696. scene.database = database;
  63697. onSuccess(plugin, data, responseURL);
  63698. };
  63699. var request = null;
  63700. var pluginDisposed = false;
  63701. var onDisposeObservable = plugin.onDisposeObservable;
  63702. if (onDisposeObservable) {
  63703. onDisposeObservable.add(function () {
  63704. pluginDisposed = true;
  63705. if (request) {
  63706. request.abort();
  63707. request = null;
  63708. }
  63709. onDispose();
  63710. });
  63711. }
  63712. var manifestChecked = function () {
  63713. if (pluginDisposed) {
  63714. return;
  63715. }
  63716. var url = rootUrl + sceneFilename;
  63717. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  63718. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  63719. } : undefined, database, useArrayBuffer, function (request, exception) {
  63720. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  63721. });
  63722. };
  63723. if (directLoad) {
  63724. dataCallback(directLoad);
  63725. return plugin;
  63726. }
  63727. if (rootUrl.indexOf("file:") === -1) {
  63728. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  63729. if (canUseOfflineSupport) {
  63730. // Also check for exceptions
  63731. var exceptionFound = false;
  63732. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  63733. var regex = _a[_i];
  63734. if (regex.test(rootUrl + sceneFilename)) {
  63735. exceptionFound = true;
  63736. break;
  63737. }
  63738. }
  63739. canUseOfflineSupport = !exceptionFound;
  63740. }
  63741. if (canUseOfflineSupport) {
  63742. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  63743. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  63744. }
  63745. else {
  63746. manifestChecked();
  63747. }
  63748. }
  63749. else {
  63750. var fileOrString = sceneFilename;
  63751. if (fileOrString.name) {
  63752. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  63753. }
  63754. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  63755. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  63756. }
  63757. else {
  63758. onError("Unable to find file named " + sceneFilename);
  63759. }
  63760. }
  63761. return plugin;
  63762. };
  63763. // Public functions
  63764. SceneLoader.GetPluginForExtension = function (extension) {
  63765. return SceneLoader._getPluginForExtension(extension).plugin;
  63766. };
  63767. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  63768. return !!SceneLoader._registeredPlugins[extension];
  63769. };
  63770. SceneLoader.RegisterPlugin = function (plugin) {
  63771. if (typeof plugin.extensions === "string") {
  63772. var extension = plugin.extensions;
  63773. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  63774. plugin: plugin,
  63775. isBinary: false
  63776. };
  63777. }
  63778. else {
  63779. var extensions = plugin.extensions;
  63780. Object.keys(extensions).forEach(function (extension) {
  63781. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  63782. plugin: plugin,
  63783. isBinary: extensions[extension].isBinary
  63784. };
  63785. });
  63786. }
  63787. };
  63788. /**
  63789. * Import meshes into a scene
  63790. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  63791. * @param rootUrl a string that defines the root url for scene and resources
  63792. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63793. * @param scene the instance of BABYLON.Scene to append to
  63794. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  63795. * @param onProgress a callback with a progress event for each file being loaded
  63796. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63797. * @param pluginExtension the extension used to determine the plugin
  63798. * @returns The loaded plugin
  63799. */
  63800. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63801. if (onSuccess === void 0) { onSuccess = null; }
  63802. if (onProgress === void 0) { onProgress = null; }
  63803. if (onError === void 0) { onError = null; }
  63804. if (pluginExtension === void 0) { pluginExtension = null; }
  63805. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63806. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63807. return null;
  63808. }
  63809. var loadingToken = {};
  63810. scene._addPendingData(loadingToken);
  63811. var disposeHandler = function () {
  63812. scene._removePendingData(loadingToken);
  63813. };
  63814. var errorHandler = function (message, exception) {
  63815. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  63816. if (onError) {
  63817. onError(scene, errorMessage, exception);
  63818. }
  63819. else {
  63820. BABYLON.Tools.Error(errorMessage);
  63821. // should the exception be thrown?
  63822. }
  63823. disposeHandler();
  63824. };
  63825. var progressHandler = onProgress ? function (event) {
  63826. try {
  63827. onProgress(event);
  63828. }
  63829. catch (e) {
  63830. errorHandler("Error in onProgress callback", e);
  63831. }
  63832. } : undefined;
  63833. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  63834. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  63835. if (onSuccess) {
  63836. try {
  63837. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  63838. }
  63839. catch (e) {
  63840. errorHandler("Error in onSuccess callback", e);
  63841. }
  63842. }
  63843. scene._removePendingData(loadingToken);
  63844. };
  63845. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63846. if (plugin.rewriteRootURL) {
  63847. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  63848. }
  63849. if (sceneFilename === "") {
  63850. if (sceneFilename === "") {
  63851. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63852. }
  63853. }
  63854. if (plugin.importMesh) {
  63855. var syncedPlugin = plugin;
  63856. var meshes = new Array();
  63857. var particleSystems = new Array();
  63858. var skeletons = new Array();
  63859. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  63860. return;
  63861. }
  63862. scene.loadingPluginName = plugin.name;
  63863. successHandler(meshes, particleSystems, skeletons, []);
  63864. }
  63865. else {
  63866. var asyncedPlugin = plugin;
  63867. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  63868. scene.loadingPluginName = plugin.name;
  63869. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  63870. }).catch(function (error) {
  63871. errorHandler(error.message, error);
  63872. });
  63873. }
  63874. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63875. };
  63876. /**
  63877. * Import meshes into a scene
  63878. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  63879. * @param rootUrl a string that defines the root url for scene and resources
  63880. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63881. * @param scene the instance of BABYLON.Scene to append to
  63882. * @param onProgress a callback with a progress event for each file being loaded
  63883. * @param pluginExtension the extension used to determine the plugin
  63884. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  63885. */
  63886. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63887. if (onProgress === void 0) { onProgress = null; }
  63888. if (pluginExtension === void 0) { pluginExtension = null; }
  63889. return new Promise(function (resolve, reject) {
  63890. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  63891. resolve({
  63892. meshes: meshes,
  63893. particleSystems: particleSystems,
  63894. skeletons: skeletons,
  63895. animationGroups: animationGroups
  63896. });
  63897. }, onProgress, function (scene, message, exception) {
  63898. reject(exception || new Error(message));
  63899. });
  63900. });
  63901. };
  63902. /**
  63903. * Load a scene
  63904. * @param rootUrl a string that defines the root url for scene and resources
  63905. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63906. * @param engine is the instance of BABYLON.Engine to use to create the scene
  63907. * @param onSuccess a callback with the scene when import succeeds
  63908. * @param onProgress a callback with a progress event for each file being loaded
  63909. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63910. * @param pluginExtension the extension used to determine the plugin
  63911. * @returns The loaded plugin
  63912. */
  63913. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  63914. if (onSuccess === void 0) { onSuccess = null; }
  63915. if (onProgress === void 0) { onProgress = null; }
  63916. if (onError === void 0) { onError = null; }
  63917. if (pluginExtension === void 0) { pluginExtension = null; }
  63918. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  63919. };
  63920. /**
  63921. * Load a scene
  63922. * @param rootUrl a string that defines the root url for scene and resources
  63923. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63924. * @param engine is the instance of BABYLON.Engine to use to create the scene
  63925. * @param onProgress a callback with a progress event for each file being loaded
  63926. * @param pluginExtension the extension used to determine the plugin
  63927. * @returns The loaded scene
  63928. */
  63929. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  63930. if (onProgress === void 0) { onProgress = null; }
  63931. if (pluginExtension === void 0) { pluginExtension = null; }
  63932. return new Promise(function (resolve, reject) {
  63933. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  63934. resolve(scene);
  63935. }, onProgress, function (scene, message, exception) {
  63936. reject(exception || new Error(message));
  63937. }, pluginExtension);
  63938. });
  63939. };
  63940. /**
  63941. * Append a scene
  63942. * @param rootUrl a string that defines the root url for scene and resources
  63943. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63944. * @param scene is the instance of BABYLON.Scene to append to
  63945. * @param onSuccess a callback with the scene when import succeeds
  63946. * @param onProgress a callback with a progress event for each file being loaded
  63947. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63948. * @param pluginExtension the extension used to determine the plugin
  63949. * @returns The loaded plugin
  63950. */
  63951. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63952. if (onSuccess === void 0) { onSuccess = null; }
  63953. if (onProgress === void 0) { onProgress = null; }
  63954. if (onError === void 0) { onError = null; }
  63955. if (pluginExtension === void 0) { pluginExtension = null; }
  63956. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63957. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63958. return null;
  63959. }
  63960. if (SceneLoader.ShowLoadingScreen) {
  63961. scene.getEngine().displayLoadingUI();
  63962. }
  63963. var loadingToken = {};
  63964. scene._addPendingData(loadingToken);
  63965. var disposeHandler = function () {
  63966. scene._removePendingData(loadingToken);
  63967. scene.getEngine().hideLoadingUI();
  63968. };
  63969. var errorHandler = function (message, exception) {
  63970. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63971. if (onError) {
  63972. onError(scene, errorMessage, exception);
  63973. }
  63974. else {
  63975. BABYLON.Tools.Error(errorMessage);
  63976. // should the exception be thrown?
  63977. }
  63978. disposeHandler();
  63979. };
  63980. var progressHandler = onProgress ? function (event) {
  63981. try {
  63982. onProgress(event);
  63983. }
  63984. catch (e) {
  63985. errorHandler("Error in onProgress callback", e);
  63986. }
  63987. } : undefined;
  63988. var successHandler = function () {
  63989. if (onSuccess) {
  63990. try {
  63991. onSuccess(scene);
  63992. }
  63993. catch (e) {
  63994. errorHandler("Error in onSuccess callback", e);
  63995. }
  63996. }
  63997. scene._removePendingData(loadingToken);
  63998. };
  63999. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  64000. if (sceneFilename === "") {
  64001. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  64002. }
  64003. if (plugin.load) {
  64004. var syncedPlugin = plugin;
  64005. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  64006. return;
  64007. }
  64008. scene.loadingPluginName = plugin.name;
  64009. successHandler();
  64010. }
  64011. else {
  64012. var asyncedPlugin = plugin;
  64013. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  64014. scene.loadingPluginName = plugin.name;
  64015. successHandler();
  64016. }).catch(function (error) {
  64017. errorHandler(error.message, error);
  64018. });
  64019. }
  64020. if (SceneLoader.ShowLoadingScreen) {
  64021. scene.executeWhenReady(function () {
  64022. scene.getEngine().hideLoadingUI();
  64023. });
  64024. }
  64025. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  64026. };
  64027. /**
  64028. * Append a scene
  64029. * @param rootUrl a string that defines the root url for scene and resources
  64030. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  64031. * @param scene is the instance of BABYLON.Scene to append to
  64032. * @param onProgress a callback with a progress event for each file being loaded
  64033. * @param pluginExtension the extension used to determine the plugin
  64034. * @returns The given scene
  64035. */
  64036. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  64037. if (onProgress === void 0) { onProgress = null; }
  64038. if (pluginExtension === void 0) { pluginExtension = null; }
  64039. return new Promise(function (resolve, reject) {
  64040. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  64041. resolve(scene);
  64042. }, onProgress, function (scene, message, exception) {
  64043. reject(exception || new Error(message));
  64044. }, pluginExtension);
  64045. });
  64046. };
  64047. /**
  64048. * Load a scene into an asset container
  64049. * @param rootUrl a string that defines the root url for scene and resources
  64050. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  64051. * @param scene is the instance of BABYLON.Scene to append to
  64052. * @param onSuccess a callback with the scene when import succeeds
  64053. * @param onProgress a callback with a progress event for each file being loaded
  64054. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  64055. * @param pluginExtension the extension used to determine the plugin
  64056. * @returns The loaded plugin
  64057. */
  64058. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  64059. if (onSuccess === void 0) { onSuccess = null; }
  64060. if (onProgress === void 0) { onProgress = null; }
  64061. if (onError === void 0) { onError = null; }
  64062. if (pluginExtension === void 0) { pluginExtension = null; }
  64063. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  64064. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  64065. return null;
  64066. }
  64067. var loadingToken = {};
  64068. scene._addPendingData(loadingToken);
  64069. var disposeHandler = function () {
  64070. scene._removePendingData(loadingToken);
  64071. };
  64072. var errorHandler = function (message, exception) {
  64073. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  64074. if (onError) {
  64075. onError(scene, errorMessage, exception);
  64076. }
  64077. else {
  64078. BABYLON.Tools.Error(errorMessage);
  64079. // should the exception be thrown?
  64080. }
  64081. disposeHandler();
  64082. };
  64083. var progressHandler = onProgress ? function (event) {
  64084. try {
  64085. onProgress(event);
  64086. }
  64087. catch (e) {
  64088. errorHandler("Error in onProgress callback", e);
  64089. }
  64090. } : undefined;
  64091. var successHandler = function (assets) {
  64092. if (onSuccess) {
  64093. try {
  64094. onSuccess(assets);
  64095. }
  64096. catch (e) {
  64097. errorHandler("Error in onSuccess callback", e);
  64098. }
  64099. }
  64100. scene._removePendingData(loadingToken);
  64101. };
  64102. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  64103. if (plugin.loadAssetContainer) {
  64104. var syncedPlugin = plugin;
  64105. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  64106. if (!assetContainer) {
  64107. return;
  64108. }
  64109. scene.loadingPluginName = plugin.name;
  64110. successHandler(assetContainer);
  64111. }
  64112. else if (plugin.loadAssetContainerAsync) {
  64113. var asyncedPlugin = plugin;
  64114. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  64115. scene.loadingPluginName = plugin.name;
  64116. successHandler(assetContainer);
  64117. }).catch(function (error) {
  64118. errorHandler(error.message, error);
  64119. });
  64120. }
  64121. else {
  64122. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  64123. }
  64124. if (SceneLoader.ShowLoadingScreen) {
  64125. scene.executeWhenReady(function () {
  64126. scene.getEngine().hideLoadingUI();
  64127. });
  64128. }
  64129. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  64130. };
  64131. /**
  64132. * Load a scene into an asset container
  64133. * @param rootUrl a string that defines the root url for scene and resources
  64134. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  64135. * @param scene is the instance of BABYLON.Scene to append to
  64136. * @param onProgress a callback with a progress event for each file being loaded
  64137. * @param pluginExtension the extension used to determine the plugin
  64138. * @returns The loaded asset container
  64139. */
  64140. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  64141. if (onProgress === void 0) { onProgress = null; }
  64142. if (pluginExtension === void 0) { pluginExtension = null; }
  64143. return new Promise(function (resolve, reject) {
  64144. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  64145. resolve(assetContainer);
  64146. }, onProgress, function (scene, message, exception) {
  64147. reject(exception || new Error(message));
  64148. }, pluginExtension);
  64149. });
  64150. };
  64151. // Flags
  64152. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  64153. SceneLoader._ShowLoadingScreen = true;
  64154. SceneLoader._CleanBoneMatrixWeights = false;
  64155. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  64156. // Members
  64157. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  64158. SceneLoader._registeredPlugins = {};
  64159. return SceneLoader;
  64160. }());
  64161. BABYLON.SceneLoader = SceneLoader;
  64162. ;
  64163. })(BABYLON || (BABYLON = {}));
  64164. //# sourceMappingURL=babylon.sceneLoader.js.map
  64165. "use strict";
  64166. var BABYLON;
  64167. (function (BABYLON) {
  64168. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  64169. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  64170. var parsedMaterial = parsedData.materials[index];
  64171. if (parsedMaterial.id === id) {
  64172. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  64173. }
  64174. }
  64175. return null;
  64176. };
  64177. var isDescendantOf = function (mesh, names, hierarchyIds) {
  64178. for (var i in names) {
  64179. if (mesh.name === names[i]) {
  64180. hierarchyIds.push(mesh.id);
  64181. return true;
  64182. }
  64183. }
  64184. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  64185. hierarchyIds.push(mesh.id);
  64186. return true;
  64187. }
  64188. return false;
  64189. };
  64190. var logOperation = function (operation, producer) {
  64191. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  64192. };
  64193. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  64194. if (addToScene === void 0) { addToScene = false; }
  64195. var container = new BABYLON.AssetContainer(scene);
  64196. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  64197. // when SceneLoader.debugLogging = true (default), or exception encountered.
  64198. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  64199. // and avoid problems with multiple concurrent .babylon loads.
  64200. var log = "importScene has failed JSON parse";
  64201. try {
  64202. var parsedData = JSON.parse(data);
  64203. log = "";
  64204. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  64205. var index;
  64206. var cache;
  64207. // Lights
  64208. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  64209. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  64210. var parsedLight = parsedData.lights[index];
  64211. var light = BABYLON.Light.Parse(parsedLight, scene);
  64212. if (light) {
  64213. container.lights.push(light);
  64214. log += (index === 0 ? "\n\tLights:" : "");
  64215. log += "\n\t\t" + light.toString(fullDetails);
  64216. }
  64217. }
  64218. }
  64219. // Animations
  64220. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  64221. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  64222. var parsedAnimation = parsedData.animations[index];
  64223. var animation = BABYLON.Animation.Parse(parsedAnimation);
  64224. scene.animations.push(animation);
  64225. container.animations.push(animation);
  64226. log += (index === 0 ? "\n\tAnimations:" : "");
  64227. log += "\n\t\t" + animation.toString(fullDetails);
  64228. }
  64229. }
  64230. // Materials
  64231. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  64232. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  64233. var parsedMaterial = parsedData.materials[index];
  64234. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  64235. container.materials.push(mat);
  64236. log += (index === 0 ? "\n\tMaterials:" : "");
  64237. log += "\n\t\t" + mat.toString(fullDetails);
  64238. }
  64239. }
  64240. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  64241. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  64242. var parsedMultiMaterial = parsedData.multiMaterials[index];
  64243. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  64244. container.multiMaterials.push(mmat);
  64245. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  64246. log += "\n\t\t" + mmat.toString(fullDetails);
  64247. }
  64248. }
  64249. // Morph targets
  64250. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  64251. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  64252. var managerData = _a[_i];
  64253. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  64254. }
  64255. }
  64256. // Skeletons
  64257. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  64258. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  64259. var parsedSkeleton = parsedData.skeletons[index];
  64260. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  64261. container.skeletons.push(skeleton);
  64262. log += (index === 0 ? "\n\tSkeletons:" : "");
  64263. log += "\n\t\t" + skeleton.toString(fullDetails);
  64264. }
  64265. }
  64266. // Geometries
  64267. var geometries = parsedData.geometries;
  64268. if (geometries !== undefined && geometries !== null) {
  64269. var addedGeometry = new Array();
  64270. // Boxes
  64271. var boxes = geometries.boxes;
  64272. if (boxes !== undefined && boxes !== null) {
  64273. for (index = 0, cache = boxes.length; index < cache; index++) {
  64274. var parsedBox = boxes[index];
  64275. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  64276. }
  64277. }
  64278. // Spheres
  64279. var spheres = geometries.spheres;
  64280. if (spheres !== undefined && spheres !== null) {
  64281. for (index = 0, cache = spheres.length; index < cache; index++) {
  64282. var parsedSphere = spheres[index];
  64283. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  64284. }
  64285. }
  64286. // Cylinders
  64287. var cylinders = geometries.cylinders;
  64288. if (cylinders !== undefined && cylinders !== null) {
  64289. for (index = 0, cache = cylinders.length; index < cache; index++) {
  64290. var parsedCylinder = cylinders[index];
  64291. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  64292. }
  64293. }
  64294. // Toruses
  64295. var toruses = geometries.toruses;
  64296. if (toruses !== undefined && toruses !== null) {
  64297. for (index = 0, cache = toruses.length; index < cache; index++) {
  64298. var parsedTorus = toruses[index];
  64299. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  64300. }
  64301. }
  64302. // Grounds
  64303. var grounds = geometries.grounds;
  64304. if (grounds !== undefined && grounds !== null) {
  64305. for (index = 0, cache = grounds.length; index < cache; index++) {
  64306. var parsedGround = grounds[index];
  64307. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  64308. }
  64309. }
  64310. // Planes
  64311. var planes = geometries.planes;
  64312. if (planes !== undefined && planes !== null) {
  64313. for (index = 0, cache = planes.length; index < cache; index++) {
  64314. var parsedPlane = planes[index];
  64315. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  64316. }
  64317. }
  64318. // TorusKnots
  64319. var torusKnots = geometries.torusKnots;
  64320. if (torusKnots !== undefined && torusKnots !== null) {
  64321. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  64322. var parsedTorusKnot = torusKnots[index];
  64323. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  64324. }
  64325. }
  64326. // VertexData
  64327. var vertexData = geometries.vertexData;
  64328. if (vertexData !== undefined && vertexData !== null) {
  64329. for (index = 0, cache = vertexData.length; index < cache; index++) {
  64330. var parsedVertexData = vertexData[index];
  64331. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  64332. }
  64333. }
  64334. addedGeometry.forEach(function (g) {
  64335. if (g) {
  64336. container.geometries.push(g);
  64337. }
  64338. });
  64339. }
  64340. // Transform nodes
  64341. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  64342. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  64343. var parsedTransformNode = parsedData.transformNodes[index];
  64344. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  64345. container.transformNodes.push(node);
  64346. }
  64347. }
  64348. // Meshes
  64349. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  64350. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  64351. var parsedMesh = parsedData.meshes[index];
  64352. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  64353. container.meshes.push(mesh);
  64354. log += (index === 0 ? "\n\tMeshes:" : "");
  64355. log += "\n\t\t" + mesh.toString(fullDetails);
  64356. }
  64357. }
  64358. // Cameras
  64359. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  64360. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  64361. var parsedCamera = parsedData.cameras[index];
  64362. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  64363. container.cameras.push(camera);
  64364. log += (index === 0 ? "\n\tCameras:" : "");
  64365. log += "\n\t\t" + camera.toString(fullDetails);
  64366. }
  64367. }
  64368. // Browsing all the graph to connect the dots
  64369. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  64370. var camera = scene.cameras[index];
  64371. if (camera._waitingParentId) {
  64372. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  64373. camera._waitingParentId = null;
  64374. }
  64375. }
  64376. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  64377. var light_1 = scene.lights[index];
  64378. if (light_1 && light_1._waitingParentId) {
  64379. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  64380. light_1._waitingParentId = null;
  64381. }
  64382. }
  64383. // Sounds
  64384. // TODO: add sound
  64385. var loadedSounds = [];
  64386. var loadedSound;
  64387. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  64388. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  64389. var parsedSound = parsedData.sounds[index];
  64390. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64391. if (!parsedSound.url)
  64392. parsedSound.url = parsedSound.name;
  64393. if (!loadedSounds[parsedSound.url]) {
  64394. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  64395. loadedSounds[parsedSound.url] = loadedSound;
  64396. container.sounds.push(loadedSound);
  64397. }
  64398. else {
  64399. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  64400. }
  64401. }
  64402. else {
  64403. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  64404. }
  64405. }
  64406. }
  64407. loadedSounds = [];
  64408. // Connect parents & children and parse actions
  64409. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  64410. var transformNode = scene.transformNodes[index];
  64411. if (transformNode._waitingParentId) {
  64412. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  64413. transformNode._waitingParentId = null;
  64414. }
  64415. }
  64416. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  64417. var mesh = scene.meshes[index];
  64418. if (mesh._waitingParentId) {
  64419. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  64420. mesh._waitingParentId = null;
  64421. }
  64422. if (mesh._waitingActions) {
  64423. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  64424. mesh._waitingActions = null;
  64425. }
  64426. }
  64427. // freeze world matrix application
  64428. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  64429. var currentMesh = scene.meshes[index];
  64430. if (currentMesh._waitingFreezeWorldMatrix) {
  64431. currentMesh.freezeWorldMatrix();
  64432. currentMesh._waitingFreezeWorldMatrix = null;
  64433. }
  64434. else {
  64435. currentMesh.computeWorldMatrix(true);
  64436. }
  64437. }
  64438. // Particles Systems
  64439. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  64440. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  64441. var parsedParticleSystem = parsedData.particleSystems[index];
  64442. if (parsedParticleSystem.activeParticleCount) {
  64443. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  64444. container.particleSystems.push(ps);
  64445. }
  64446. else {
  64447. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  64448. container.particleSystems.push(ps);
  64449. }
  64450. }
  64451. }
  64452. // Lens flares
  64453. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  64454. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  64455. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  64456. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  64457. container.lensFlareSystems.push(lf);
  64458. }
  64459. }
  64460. // Shadows
  64461. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  64462. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  64463. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  64464. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  64465. container.shadowGenerators.push(sg);
  64466. }
  64467. }
  64468. // Lights exclusions / inclusions
  64469. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  64470. var light_2 = scene.lights[index];
  64471. // Excluded check
  64472. if (light_2._excludedMeshesIds.length > 0) {
  64473. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  64474. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  64475. if (excludedMesh) {
  64476. light_2.excludedMeshes.push(excludedMesh);
  64477. }
  64478. }
  64479. light_2._excludedMeshesIds = [];
  64480. }
  64481. // Included check
  64482. if (light_2._includedOnlyMeshesIds.length > 0) {
  64483. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  64484. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  64485. if (includedOnlyMesh) {
  64486. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  64487. }
  64488. }
  64489. light_2._includedOnlyMeshesIds = [];
  64490. }
  64491. }
  64492. // Actions (scene)
  64493. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  64494. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  64495. }
  64496. if (!addToScene) {
  64497. container.removeAllFromScene();
  64498. }
  64499. }
  64500. catch (err) {
  64501. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  64502. if (onError) {
  64503. onError(msg, err);
  64504. }
  64505. else {
  64506. BABYLON.Tools.Log(msg);
  64507. throw err;
  64508. }
  64509. }
  64510. finally {
  64511. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  64512. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  64513. }
  64514. }
  64515. return container;
  64516. };
  64517. BABYLON.SceneLoader.RegisterPlugin({
  64518. name: "babylon.js",
  64519. extensions: ".babylon",
  64520. canDirectLoad: function (data) {
  64521. if (data.indexOf("babylon") !== -1) {
  64522. return true;
  64523. }
  64524. return false;
  64525. },
  64526. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  64527. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  64528. // when SceneLoader.debugLogging = true (default), or exception encountered.
  64529. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  64530. // and avoid problems with multiple concurrent .babylon loads.
  64531. var log = "importMesh has failed JSON parse";
  64532. try {
  64533. var parsedData = JSON.parse(data);
  64534. log = "";
  64535. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  64536. if (!meshesNames) {
  64537. meshesNames = null;
  64538. }
  64539. else if (!Array.isArray(meshesNames)) {
  64540. meshesNames = [meshesNames];
  64541. }
  64542. var hierarchyIds = new Array();
  64543. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  64544. var loadedSkeletonsIds = [];
  64545. var loadedMaterialsIds = [];
  64546. var index;
  64547. var cache;
  64548. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  64549. var parsedMesh = parsedData.meshes[index];
  64550. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  64551. if (meshesNames !== null) {
  64552. // Remove found mesh name from list.
  64553. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  64554. }
  64555. //Geometry?
  64556. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  64557. //does the file contain geometries?
  64558. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  64559. //find the correct geometry and add it to the scene
  64560. var found = false;
  64561. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  64562. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  64563. return;
  64564. }
  64565. else {
  64566. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  64567. if (parsedGeometryData.id === parsedMesh.geometryId) {
  64568. switch (geometryType) {
  64569. case "boxes":
  64570. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  64571. break;
  64572. case "spheres":
  64573. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  64574. break;
  64575. case "cylinders":
  64576. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  64577. break;
  64578. case "toruses":
  64579. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  64580. break;
  64581. case "grounds":
  64582. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  64583. break;
  64584. case "planes":
  64585. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  64586. break;
  64587. case "torusKnots":
  64588. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  64589. break;
  64590. case "vertexData":
  64591. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  64592. break;
  64593. }
  64594. found = true;
  64595. }
  64596. });
  64597. }
  64598. });
  64599. if (found === false) {
  64600. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  64601. }
  64602. }
  64603. }
  64604. // Material ?
  64605. if (parsedMesh.materialId) {
  64606. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  64607. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  64608. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  64609. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  64610. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  64611. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  64612. var subMatId = parsedMultiMaterial.materials[matIndex];
  64613. loadedMaterialsIds.push(subMatId);
  64614. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  64615. if (mat) {
  64616. log += "\n\tMaterial " + mat.toString(fullDetails);
  64617. }
  64618. }
  64619. loadedMaterialsIds.push(parsedMultiMaterial.id);
  64620. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  64621. if (mmat) {
  64622. materialFound = true;
  64623. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  64624. }
  64625. break;
  64626. }
  64627. }
  64628. }
  64629. if (materialFound === false) {
  64630. loadedMaterialsIds.push(parsedMesh.materialId);
  64631. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  64632. if (!mat) {
  64633. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  64634. }
  64635. else {
  64636. log += "\n\tMaterial " + mat.toString(fullDetails);
  64637. }
  64638. }
  64639. }
  64640. // Skeleton ?
  64641. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  64642. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  64643. if (skeletonAlreadyLoaded === false) {
  64644. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  64645. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  64646. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  64647. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  64648. skeletons.push(skeleton);
  64649. loadedSkeletonsIds.push(parsedSkeleton.id);
  64650. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  64651. }
  64652. }
  64653. }
  64654. }
  64655. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  64656. meshes.push(mesh);
  64657. log += "\n\tMesh " + mesh.toString(fullDetails);
  64658. }
  64659. }
  64660. // Connecting parents
  64661. var currentMesh;
  64662. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  64663. currentMesh = scene.meshes[index];
  64664. if (currentMesh._waitingParentId) {
  64665. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  64666. currentMesh._waitingParentId = null;
  64667. }
  64668. }
  64669. // freeze and compute world matrix application
  64670. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  64671. currentMesh = scene.meshes[index];
  64672. if (currentMesh._waitingFreezeWorldMatrix) {
  64673. currentMesh.freezeWorldMatrix();
  64674. currentMesh._waitingFreezeWorldMatrix = null;
  64675. }
  64676. else {
  64677. currentMesh.computeWorldMatrix(true);
  64678. }
  64679. }
  64680. }
  64681. // Particles
  64682. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  64683. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  64684. var parsedParticleSystem = parsedData.particleSystems[index];
  64685. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  64686. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  64687. }
  64688. }
  64689. }
  64690. return true;
  64691. }
  64692. catch (err) {
  64693. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  64694. if (onError) {
  64695. onError(msg, err);
  64696. }
  64697. else {
  64698. BABYLON.Tools.Log(msg);
  64699. throw err;
  64700. }
  64701. }
  64702. finally {
  64703. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  64704. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  64705. }
  64706. }
  64707. return false;
  64708. },
  64709. load: function (scene, data, rootUrl, onError) {
  64710. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  64711. // when SceneLoader.debugLogging = true (default), or exception encountered.
  64712. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  64713. // and avoid problems with multiple concurrent .babylon loads.
  64714. var log = "importScene has failed JSON parse";
  64715. try {
  64716. var parsedData = JSON.parse(data);
  64717. log = "";
  64718. // Scene
  64719. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  64720. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  64721. }
  64722. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  64723. scene.autoClear = parsedData.autoClear;
  64724. }
  64725. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  64726. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  64727. }
  64728. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  64729. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  64730. }
  64731. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  64732. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  64733. }
  64734. // Fog
  64735. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  64736. scene.fogMode = parsedData.fogMode;
  64737. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  64738. scene.fogStart = parsedData.fogStart;
  64739. scene.fogEnd = parsedData.fogEnd;
  64740. scene.fogDensity = parsedData.fogDensity;
  64741. log += "\tFog mode for scene: ";
  64742. switch (scene.fogMode) {
  64743. // getters not compiling, so using hardcoded
  64744. case 1:
  64745. log += "exp\n";
  64746. break;
  64747. case 2:
  64748. log += "exp2\n";
  64749. break;
  64750. case 3:
  64751. log += "linear\n";
  64752. break;
  64753. }
  64754. }
  64755. //Physics
  64756. if (parsedData.physicsEnabled) {
  64757. var physicsPlugin;
  64758. if (parsedData.physicsEngine === "cannon") {
  64759. physicsPlugin = new BABYLON.CannonJSPlugin();
  64760. }
  64761. else if (parsedData.physicsEngine === "oimo") {
  64762. physicsPlugin = new BABYLON.OimoJSPlugin();
  64763. }
  64764. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  64765. //else - default engine, which is currently oimo
  64766. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  64767. scene.enablePhysics(physicsGravity, physicsPlugin);
  64768. }
  64769. // Metadata
  64770. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  64771. scene.metadata = parsedData.metadata;
  64772. }
  64773. //collisions, if defined. otherwise, default is true
  64774. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  64775. scene.collisionsEnabled = parsedData.collisionsEnabled;
  64776. }
  64777. scene.workerCollisions = !!parsedData.workerCollisions;
  64778. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  64779. if (!container) {
  64780. return false;
  64781. }
  64782. if (parsedData.autoAnimate) {
  64783. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  64784. }
  64785. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  64786. scene.setActiveCameraByID(parsedData.activeCameraID);
  64787. }
  64788. // Environment texture
  64789. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  64790. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  64791. if (parsedData.createDefaultSkybox === true) {
  64792. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  64793. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  64794. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  64795. }
  64796. }
  64797. // Finish
  64798. return true;
  64799. }
  64800. catch (err) {
  64801. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  64802. if (onError) {
  64803. onError(msg, err);
  64804. }
  64805. else {
  64806. BABYLON.Tools.Log(msg);
  64807. throw err;
  64808. }
  64809. }
  64810. finally {
  64811. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  64812. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  64813. }
  64814. }
  64815. return false;
  64816. },
  64817. loadAssetContainer: function (scene, data, rootUrl, onError) {
  64818. var container = loadAssetContainer(scene, data, rootUrl, onError);
  64819. return container;
  64820. }
  64821. });
  64822. })(BABYLON || (BABYLON = {}));
  64823. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  64824. "use strict";
  64825. var BABYLON;
  64826. (function (BABYLON) {
  64827. var FilesInput = /** @class */ (function () {
  64828. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  64829. this.onProcessFileCallback = function () { return true; };
  64830. this._engine = engine;
  64831. this._currentScene = scene;
  64832. this._sceneLoadedCallback = sceneLoadedCallback;
  64833. this._progressCallback = progressCallback;
  64834. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  64835. this._textureLoadingCallback = textureLoadingCallback;
  64836. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  64837. this._onReloadCallback = onReloadCallback;
  64838. this._errorCallback = errorCallback;
  64839. }
  64840. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  64841. var _this = this;
  64842. if (elementToMonitor) {
  64843. this._elementToMonitor = elementToMonitor;
  64844. this._dragEnterHandler = function (e) { _this.drag(e); };
  64845. this._dragOverHandler = function (e) { _this.drag(e); };
  64846. this._dropHandler = function (e) { _this.drop(e); };
  64847. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  64848. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  64849. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  64850. }
  64851. };
  64852. FilesInput.prototype.dispose = function () {
  64853. if (!this._elementToMonitor) {
  64854. return;
  64855. }
  64856. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  64857. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  64858. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  64859. };
  64860. FilesInput.prototype.renderFunction = function () {
  64861. if (this._additionalRenderLoopLogicCallback) {
  64862. this._additionalRenderLoopLogicCallback();
  64863. }
  64864. if (this._currentScene) {
  64865. if (this._textureLoadingCallback) {
  64866. var remaining = this._currentScene.getWaitingItemsCount();
  64867. if (remaining > 0) {
  64868. this._textureLoadingCallback(remaining);
  64869. }
  64870. }
  64871. this._currentScene.render();
  64872. }
  64873. };
  64874. FilesInput.prototype.drag = function (e) {
  64875. e.stopPropagation();
  64876. e.preventDefault();
  64877. };
  64878. FilesInput.prototype.drop = function (eventDrop) {
  64879. eventDrop.stopPropagation();
  64880. eventDrop.preventDefault();
  64881. this.loadFiles(eventDrop);
  64882. };
  64883. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  64884. var _this = this;
  64885. var reader = folder.createReader();
  64886. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  64887. reader.readEntries(function (entries) {
  64888. remaining.count += entries.length;
  64889. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  64890. var entry = entries_1[_i];
  64891. if (entry.isFile) {
  64892. entry.file(function (file) {
  64893. file.correctName = relativePath + file.name;
  64894. files.push(file);
  64895. if (--remaining.count === 0) {
  64896. callback();
  64897. }
  64898. });
  64899. }
  64900. else if (entry.isDirectory) {
  64901. _this._traverseFolder(entry, files, remaining, callback);
  64902. }
  64903. }
  64904. if (--remaining.count) {
  64905. callback();
  64906. }
  64907. });
  64908. };
  64909. FilesInput.prototype._processFiles = function (files) {
  64910. for (var i = 0; i < files.length; i++) {
  64911. var name = files[i].correctName.toLowerCase();
  64912. var extension = name.split('.').pop();
  64913. if (!this.onProcessFileCallback(files[i], name, extension)) {
  64914. continue;
  64915. }
  64916. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  64917. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  64918. this._sceneFileToLoad = files[i];
  64919. }
  64920. else {
  64921. FilesInput.FilesToLoad[name] = files[i];
  64922. }
  64923. }
  64924. };
  64925. FilesInput.prototype.loadFiles = function (event) {
  64926. var _this = this;
  64927. if (this._startingProcessingFilesCallback)
  64928. this._startingProcessingFilesCallback();
  64929. // Handling data transfer via drag'n'drop
  64930. if (event && event.dataTransfer && event.dataTransfer.files) {
  64931. this._filesToLoad = event.dataTransfer.files;
  64932. }
  64933. // Handling files from input files
  64934. if (event && event.target && event.target.files) {
  64935. this._filesToLoad = event.target.files;
  64936. }
  64937. if (this._filesToLoad && this._filesToLoad.length > 0) {
  64938. var files_1 = new Array();
  64939. var folders = [];
  64940. var items = event.dataTransfer ? event.dataTransfer.items : null;
  64941. for (var i = 0; i < this._filesToLoad.length; i++) {
  64942. var fileToLoad = this._filesToLoad[i];
  64943. var name_1 = fileToLoad.name.toLowerCase();
  64944. var entry = void 0;
  64945. fileToLoad.correctName = name_1;
  64946. if (items) {
  64947. var item = items[i];
  64948. if (item.getAsEntry) {
  64949. entry = item.getAsEntry();
  64950. }
  64951. else if (item.webkitGetAsEntry) {
  64952. entry = item.webkitGetAsEntry();
  64953. }
  64954. }
  64955. if (!entry) {
  64956. files_1.push(fileToLoad);
  64957. }
  64958. else {
  64959. if (entry.isDirectory) {
  64960. folders.push(entry);
  64961. }
  64962. else {
  64963. files_1.push(fileToLoad);
  64964. }
  64965. }
  64966. }
  64967. if (folders.length === 0) {
  64968. this._processFiles(files_1);
  64969. this._processReload();
  64970. }
  64971. else {
  64972. var remaining = { count: folders.length };
  64973. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  64974. var folder = folders_1[_i];
  64975. this._traverseFolder(folder, files_1, remaining, function () {
  64976. _this._processFiles(files_1);
  64977. if (remaining.count === 0) {
  64978. _this._processReload();
  64979. }
  64980. });
  64981. }
  64982. }
  64983. }
  64984. };
  64985. FilesInput.prototype._processReload = function () {
  64986. if (this._onReloadCallback) {
  64987. this._onReloadCallback(this._sceneFileToLoad);
  64988. }
  64989. else {
  64990. this.reload();
  64991. }
  64992. };
  64993. FilesInput.prototype.reload = function () {
  64994. var _this = this;
  64995. // If a scene file has been provided
  64996. if (this._sceneFileToLoad) {
  64997. if (this._currentScene) {
  64998. if (BABYLON.Tools.errorsCount > 0) {
  64999. BABYLON.Tools.ClearLogCache();
  65000. }
  65001. this._engine.stopRenderLoop();
  65002. this._currentScene.dispose();
  65003. }
  65004. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  65005. if (_this._progressCallback) {
  65006. _this._progressCallback(progress);
  65007. }
  65008. }).then(function (scene) {
  65009. _this._currentScene = scene;
  65010. if (_this._sceneLoadedCallback) {
  65011. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  65012. }
  65013. // Wait for textures and shaders to be ready
  65014. _this._currentScene.executeWhenReady(function () {
  65015. _this._engine.runRenderLoop(function () {
  65016. _this.renderFunction();
  65017. });
  65018. });
  65019. }).catch(function (error) {
  65020. if (_this._errorCallback) {
  65021. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  65022. }
  65023. });
  65024. }
  65025. else {
  65026. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  65027. }
  65028. };
  65029. FilesInput.FilesToLoad = {};
  65030. return FilesInput;
  65031. }());
  65032. BABYLON.FilesInput = FilesInput;
  65033. })(BABYLON || (BABYLON = {}));
  65034. //# sourceMappingURL=babylon.filesInput.js.map
  65035. "use strict";
  65036. var BABYLON;
  65037. (function (BABYLON) {
  65038. /**
  65039. * This class implement a typical dictionary using a string as key and the generic type T as value.
  65040. * The underlying implementation relies on an associative array to ensure the best performances.
  65041. * The value can be anything including 'null' but except 'undefined'
  65042. */
  65043. var StringDictionary = /** @class */ (function () {
  65044. function StringDictionary() {
  65045. this._count = 0;
  65046. this._data = {};
  65047. }
  65048. /**
  65049. * This will clear this dictionary and copy the content from the 'source' one.
  65050. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  65051. * @param source the dictionary to take the content from and copy to this dictionary
  65052. */
  65053. StringDictionary.prototype.copyFrom = function (source) {
  65054. var _this = this;
  65055. this.clear();
  65056. source.forEach(function (t, v) { return _this.add(t, v); });
  65057. };
  65058. /**
  65059. * Get a value based from its key
  65060. * @param key the given key to get the matching value from
  65061. * @return the value if found, otherwise undefined is returned
  65062. */
  65063. StringDictionary.prototype.get = function (key) {
  65064. var val = this._data[key];
  65065. if (val !== undefined) {
  65066. return val;
  65067. }
  65068. return undefined;
  65069. };
  65070. /**
  65071. * Get a value from its key or add it if it doesn't exist.
  65072. * This method will ensure you that a given key/data will be present in the dictionary.
  65073. * @param key the given key to get the matching value from
  65074. * @param factory the factory that will create the value if the key is not present in the dictionary.
  65075. * The factory will only be invoked if there's no data for the given key.
  65076. * @return the value corresponding to the key.
  65077. */
  65078. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  65079. var val = this.get(key);
  65080. if (val !== undefined) {
  65081. return val;
  65082. }
  65083. val = factory(key);
  65084. if (val) {
  65085. this.add(key, val);
  65086. }
  65087. return val;
  65088. };
  65089. /**
  65090. * Get a value from its key if present in the dictionary otherwise add it
  65091. * @param key the key to get the value from
  65092. * @param val if there's no such key/value pair in the dictionary add it with this value
  65093. * @return the value corresponding to the key
  65094. */
  65095. StringDictionary.prototype.getOrAdd = function (key, val) {
  65096. var curVal = this.get(key);
  65097. if (curVal !== undefined) {
  65098. return curVal;
  65099. }
  65100. this.add(key, val);
  65101. return val;
  65102. };
  65103. /**
  65104. * Check if there's a given key in the dictionary
  65105. * @param key the key to check for
  65106. * @return true if the key is present, false otherwise
  65107. */
  65108. StringDictionary.prototype.contains = function (key) {
  65109. return this._data[key] !== undefined;
  65110. };
  65111. /**
  65112. * Add a new key and its corresponding value
  65113. * @param key the key to add
  65114. * @param value the value corresponding to the key
  65115. * @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
  65116. */
  65117. StringDictionary.prototype.add = function (key, value) {
  65118. if (this._data[key] !== undefined) {
  65119. return false;
  65120. }
  65121. this._data[key] = value;
  65122. ++this._count;
  65123. return true;
  65124. };
  65125. StringDictionary.prototype.set = function (key, value) {
  65126. if (this._data[key] === undefined) {
  65127. return false;
  65128. }
  65129. this._data[key] = value;
  65130. return true;
  65131. };
  65132. /**
  65133. * Get the element of the given key and remove it from the dictionary
  65134. * @param key
  65135. */
  65136. StringDictionary.prototype.getAndRemove = function (key) {
  65137. var val = this.get(key);
  65138. if (val !== undefined) {
  65139. delete this._data[key];
  65140. --this._count;
  65141. return val;
  65142. }
  65143. return null;
  65144. };
  65145. /**
  65146. * Remove a key/value from the dictionary.
  65147. * @param key the key to remove
  65148. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  65149. */
  65150. StringDictionary.prototype.remove = function (key) {
  65151. if (this.contains(key)) {
  65152. delete this._data[key];
  65153. --this._count;
  65154. return true;
  65155. }
  65156. return false;
  65157. };
  65158. /**
  65159. * Clear the whole content of the dictionary
  65160. */
  65161. StringDictionary.prototype.clear = function () {
  65162. this._data = {};
  65163. this._count = 0;
  65164. };
  65165. Object.defineProperty(StringDictionary.prototype, "count", {
  65166. get: function () {
  65167. return this._count;
  65168. },
  65169. enumerable: true,
  65170. configurable: true
  65171. });
  65172. /**
  65173. * Execute a callback on each key/val of the dictionary.
  65174. * Note that you can remove any element in this dictionary in the callback implementation
  65175. * @param callback the callback to execute on a given key/value pair
  65176. */
  65177. StringDictionary.prototype.forEach = function (callback) {
  65178. for (var cur in this._data) {
  65179. var val = this._data[cur];
  65180. callback(cur, val);
  65181. }
  65182. };
  65183. /**
  65184. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  65185. * If the callback returns null or undefined the method will iterate to the next key/value pair
  65186. * Note that you can remove any element in this dictionary in the callback implementation
  65187. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  65188. */
  65189. StringDictionary.prototype.first = function (callback) {
  65190. for (var cur in this._data) {
  65191. var val = this._data[cur];
  65192. var res = callback(cur, val);
  65193. if (res) {
  65194. return res;
  65195. }
  65196. }
  65197. return null;
  65198. };
  65199. return StringDictionary;
  65200. }());
  65201. BABYLON.StringDictionary = StringDictionary;
  65202. })(BABYLON || (BABYLON = {}));
  65203. //# sourceMappingURL=babylon.stringDictionary.js.map
  65204. "use strict";
  65205. var BABYLON;
  65206. (function (BABYLON) {
  65207. var Tags = /** @class */ (function () {
  65208. function Tags() {
  65209. }
  65210. Tags.EnableFor = function (obj) {
  65211. obj._tags = obj._tags || {};
  65212. obj.hasTags = function () {
  65213. return Tags.HasTags(obj);
  65214. };
  65215. obj.addTags = function (tagsString) {
  65216. return Tags.AddTagsTo(obj, tagsString);
  65217. };
  65218. obj.removeTags = function (tagsString) {
  65219. return Tags.RemoveTagsFrom(obj, tagsString);
  65220. };
  65221. obj.matchesTagsQuery = function (tagsQuery) {
  65222. return Tags.MatchesQuery(obj, tagsQuery);
  65223. };
  65224. };
  65225. Tags.DisableFor = function (obj) {
  65226. delete obj._tags;
  65227. delete obj.hasTags;
  65228. delete obj.addTags;
  65229. delete obj.removeTags;
  65230. delete obj.matchesTagsQuery;
  65231. };
  65232. Tags.HasTags = function (obj) {
  65233. if (!obj._tags) {
  65234. return false;
  65235. }
  65236. return !BABYLON.Tools.IsEmpty(obj._tags);
  65237. };
  65238. Tags.GetTags = function (obj, asString) {
  65239. if (asString === void 0) { asString = true; }
  65240. if (!obj._tags) {
  65241. return null;
  65242. }
  65243. if (asString) {
  65244. var tagsArray = [];
  65245. for (var tag in obj._tags) {
  65246. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  65247. tagsArray.push(tag);
  65248. }
  65249. }
  65250. return tagsArray.join(" ");
  65251. }
  65252. else {
  65253. return obj._tags;
  65254. }
  65255. };
  65256. // the tags 'true' and 'false' are reserved and cannot be used as tags
  65257. // a tag cannot start with '||', '&&', and '!'
  65258. // it cannot contain whitespaces
  65259. Tags.AddTagsTo = function (obj, tagsString) {
  65260. if (!tagsString) {
  65261. return;
  65262. }
  65263. if (typeof tagsString !== "string") {
  65264. return;
  65265. }
  65266. var tags = tagsString.split(" ");
  65267. tags.forEach(function (tag, index, array) {
  65268. Tags._AddTagTo(obj, tag);
  65269. });
  65270. };
  65271. Tags._AddTagTo = function (obj, tag) {
  65272. tag = tag.trim();
  65273. if (tag === "" || tag === "true" || tag === "false") {
  65274. return;
  65275. }
  65276. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  65277. return;
  65278. }
  65279. Tags.EnableFor(obj);
  65280. obj._tags[tag] = true;
  65281. };
  65282. Tags.RemoveTagsFrom = function (obj, tagsString) {
  65283. if (!Tags.HasTags(obj)) {
  65284. return;
  65285. }
  65286. var tags = tagsString.split(" ");
  65287. for (var t in tags) {
  65288. Tags._RemoveTagFrom(obj, tags[t]);
  65289. }
  65290. };
  65291. Tags._RemoveTagFrom = function (obj, tag) {
  65292. delete obj._tags[tag];
  65293. };
  65294. Tags.MatchesQuery = function (obj, tagsQuery) {
  65295. if (tagsQuery === undefined) {
  65296. return true;
  65297. }
  65298. if (tagsQuery === "") {
  65299. return Tags.HasTags(obj);
  65300. }
  65301. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  65302. };
  65303. return Tags;
  65304. }());
  65305. BABYLON.Tags = Tags;
  65306. })(BABYLON || (BABYLON = {}));
  65307. //# sourceMappingURL=babylon.tags.js.map
  65308. "use strict";
  65309. var BABYLON;
  65310. (function (BABYLON) {
  65311. var AndOrNotEvaluator = /** @class */ (function () {
  65312. function AndOrNotEvaluator() {
  65313. }
  65314. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  65315. if (!query.match(/\([^\(\)]*\)/g)) {
  65316. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  65317. }
  65318. else {
  65319. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  65320. // remove parenthesis
  65321. r = r.slice(1, r.length - 1);
  65322. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  65323. });
  65324. }
  65325. if (query === "true") {
  65326. return true;
  65327. }
  65328. if (query === "false") {
  65329. return false;
  65330. }
  65331. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  65332. };
  65333. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  65334. evaluateCallback = evaluateCallback || (function (r) {
  65335. return r === "true" ? true : false;
  65336. });
  65337. var result;
  65338. var or = parenthesisContent.split("||");
  65339. for (var i in or) {
  65340. if (or.hasOwnProperty(i)) {
  65341. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  65342. var and = ori.split("&&");
  65343. if (and.length > 1) {
  65344. for (var j = 0; j < and.length; ++j) {
  65345. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  65346. if (andj !== "true" && andj !== "false") {
  65347. if (andj[0] === "!") {
  65348. result = !evaluateCallback(andj.substring(1));
  65349. }
  65350. else {
  65351. result = evaluateCallback(andj);
  65352. }
  65353. }
  65354. else {
  65355. result = andj === "true" ? true : false;
  65356. }
  65357. if (!result) {
  65358. ori = "false";
  65359. break;
  65360. }
  65361. }
  65362. }
  65363. if (result || ori === "true") {
  65364. result = true;
  65365. break;
  65366. }
  65367. // result equals false (or undefined)
  65368. if (ori !== "true" && ori !== "false") {
  65369. if (ori[0] === "!") {
  65370. result = !evaluateCallback(ori.substring(1));
  65371. }
  65372. else {
  65373. result = evaluateCallback(ori);
  65374. }
  65375. }
  65376. else {
  65377. result = ori === "true" ? true : false;
  65378. }
  65379. }
  65380. }
  65381. // the whole parenthesis scope is replaced by 'true' or 'false'
  65382. return result ? "true" : "false";
  65383. };
  65384. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  65385. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  65386. // remove whitespaces
  65387. r = r.replace(/[\s]/g, function () { return ""; });
  65388. return r.length % 2 ? "!" : "";
  65389. });
  65390. booleanString = booleanString.trim();
  65391. if (booleanString === "!true") {
  65392. booleanString = "false";
  65393. }
  65394. else if (booleanString === "!false") {
  65395. booleanString = "true";
  65396. }
  65397. return booleanString;
  65398. };
  65399. return AndOrNotEvaluator;
  65400. }());
  65401. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  65402. })(BABYLON || (BABYLON = {}));
  65403. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  65404. "use strict";
  65405. var BABYLON;
  65406. (function (BABYLON) {
  65407. var Database = /** @class */ (function () {
  65408. function Database(urlToScene, callbackManifestChecked) {
  65409. // Handling various flavors of prefixed version of IndexedDB
  65410. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  65411. this.callbackManifestChecked = callbackManifestChecked;
  65412. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  65413. this.db = null;
  65414. this._enableSceneOffline = false;
  65415. this._enableTexturesOffline = false;
  65416. this.manifestVersionFound = 0;
  65417. this.mustUpdateRessources = false;
  65418. this.hasReachedQuota = false;
  65419. if (!Database.IDBStorageEnabled) {
  65420. this.callbackManifestChecked(true);
  65421. }
  65422. else {
  65423. this.checkManifestFile();
  65424. }
  65425. }
  65426. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  65427. get: function () {
  65428. return this._enableSceneOffline;
  65429. },
  65430. enumerable: true,
  65431. configurable: true
  65432. });
  65433. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  65434. get: function () {
  65435. return this._enableTexturesOffline;
  65436. },
  65437. enumerable: true,
  65438. configurable: true
  65439. });
  65440. Database.prototype.checkManifestFile = function () {
  65441. var _this = this;
  65442. var noManifestFile = function () {
  65443. _this._enableSceneOffline = false;
  65444. _this._enableTexturesOffline = false;
  65445. _this.callbackManifestChecked(false);
  65446. };
  65447. var timeStampUsed = false;
  65448. var manifestURL = this.currentSceneUrl + ".manifest";
  65449. var xhr = new XMLHttpRequest();
  65450. if (navigator.onLine) {
  65451. // Adding a timestamp to by-pass browsers' cache
  65452. timeStampUsed = true;
  65453. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  65454. }
  65455. xhr.open("GET", manifestURL, true);
  65456. xhr.addEventListener("load", function () {
  65457. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65458. try {
  65459. var manifestFile = JSON.parse(xhr.response);
  65460. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  65461. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  65462. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  65463. _this.manifestVersionFound = manifestFile.version;
  65464. }
  65465. if (_this.callbackManifestChecked) {
  65466. _this.callbackManifestChecked(true);
  65467. }
  65468. }
  65469. catch (ex) {
  65470. noManifestFile();
  65471. }
  65472. }
  65473. else {
  65474. noManifestFile();
  65475. }
  65476. }, false);
  65477. xhr.addEventListener("error", function (event) {
  65478. if (timeStampUsed) {
  65479. timeStampUsed = false;
  65480. // Let's retry without the timeStamp
  65481. // It could fail when coupled with HTML5 Offline API
  65482. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  65483. xhr.open("GET", retryManifestURL, true);
  65484. xhr.send();
  65485. }
  65486. else {
  65487. noManifestFile();
  65488. }
  65489. }, false);
  65490. try {
  65491. xhr.send();
  65492. }
  65493. catch (ex) {
  65494. BABYLON.Tools.Error("Error on XHR send request.");
  65495. this.callbackManifestChecked(false);
  65496. }
  65497. };
  65498. Database.prototype.openAsync = function (successCallback, errorCallback) {
  65499. var _this = this;
  65500. var handleError = function () {
  65501. _this.isSupported = false;
  65502. if (errorCallback)
  65503. errorCallback();
  65504. };
  65505. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  65506. // Your browser doesn't support IndexedDB
  65507. this.isSupported = false;
  65508. if (errorCallback)
  65509. errorCallback();
  65510. }
  65511. else {
  65512. // If the DB hasn't been opened or created yet
  65513. if (!this.db) {
  65514. this.hasReachedQuota = false;
  65515. this.isSupported = true;
  65516. var request = this.idbFactory.open("babylonjs", 1);
  65517. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  65518. request.onerror = function (event) {
  65519. handleError();
  65520. };
  65521. // executes when a version change transaction cannot complete due to other active transactions
  65522. request.onblocked = function (event) {
  65523. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  65524. handleError();
  65525. };
  65526. // DB has been opened successfully
  65527. request.onsuccess = function (event) {
  65528. _this.db = request.result;
  65529. successCallback();
  65530. };
  65531. // Initialization of the DB. Creating Scenes & Textures stores
  65532. request.onupgradeneeded = function (event) {
  65533. _this.db = (event.target).result;
  65534. if (_this.db) {
  65535. try {
  65536. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  65537. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  65538. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  65539. }
  65540. catch (ex) {
  65541. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  65542. handleError();
  65543. }
  65544. }
  65545. };
  65546. }
  65547. else {
  65548. if (successCallback)
  65549. successCallback();
  65550. }
  65551. }
  65552. };
  65553. Database.prototype.loadImageFromDB = function (url, image) {
  65554. var _this = this;
  65555. var completeURL = Database.ReturnFullUrlLocation(url);
  65556. var saveAndLoadImage = function () {
  65557. if (!_this.hasReachedQuota && _this.db !== null) {
  65558. // the texture is not yet in the DB, let's try to save it
  65559. _this._saveImageIntoDBAsync(completeURL, image);
  65560. }
  65561. else {
  65562. image.src = url;
  65563. }
  65564. };
  65565. if (!this.mustUpdateRessources) {
  65566. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  65567. }
  65568. else {
  65569. saveAndLoadImage();
  65570. }
  65571. };
  65572. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  65573. if (this.isSupported && this.db !== null) {
  65574. var texture;
  65575. var transaction = this.db.transaction(["textures"]);
  65576. transaction.onabort = function (event) {
  65577. image.src = url;
  65578. };
  65579. transaction.oncomplete = function (event) {
  65580. var blobTextureURL;
  65581. if (texture) {
  65582. var URL = window.URL || window.webkitURL;
  65583. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  65584. image.onerror = function () {
  65585. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  65586. image.src = url;
  65587. };
  65588. image.src = blobTextureURL;
  65589. }
  65590. else {
  65591. notInDBCallback();
  65592. }
  65593. };
  65594. var getRequest = transaction.objectStore("textures").get(url);
  65595. getRequest.onsuccess = function (event) {
  65596. texture = (event.target).result;
  65597. };
  65598. getRequest.onerror = function (event) {
  65599. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  65600. image.src = url;
  65601. };
  65602. }
  65603. else {
  65604. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65605. image.src = url;
  65606. }
  65607. };
  65608. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  65609. var _this = this;
  65610. if (this.isSupported) {
  65611. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  65612. var generateBlobUrl = function () {
  65613. var blobTextureURL;
  65614. if (blob) {
  65615. var URL = window.URL || window.webkitURL;
  65616. try {
  65617. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  65618. }
  65619. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  65620. catch (ex) {
  65621. blobTextureURL = URL.createObjectURL(blob);
  65622. }
  65623. }
  65624. if (blobTextureURL) {
  65625. image.src = blobTextureURL;
  65626. }
  65627. };
  65628. if (Database.IsUASupportingBlobStorage) {
  65629. var xhr = new XMLHttpRequest(), blob;
  65630. xhr.open("GET", url, true);
  65631. xhr.responseType = "blob";
  65632. xhr.addEventListener("load", function () {
  65633. if (xhr.status === 200 && _this.db) {
  65634. // Blob as response (XHR2)
  65635. blob = xhr.response;
  65636. var transaction = _this.db.transaction(["textures"], "readwrite");
  65637. // the transaction could abort because of a QuotaExceededError error
  65638. transaction.onabort = function (event) {
  65639. try {
  65640. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  65641. var srcElement = (event.srcElement || event.target);
  65642. var error = srcElement.error;
  65643. if (error && error.name === "QuotaExceededError") {
  65644. _this.hasReachedQuota = true;
  65645. }
  65646. }
  65647. catch (ex) { }
  65648. generateBlobUrl();
  65649. };
  65650. transaction.oncomplete = function (event) {
  65651. generateBlobUrl();
  65652. };
  65653. var newTexture = { textureUrl: url, data: blob };
  65654. try {
  65655. // Put the blob into the dabase
  65656. var addRequest = transaction.objectStore("textures").put(newTexture);
  65657. addRequest.onsuccess = function (event) {
  65658. };
  65659. addRequest.onerror = function (event) {
  65660. generateBlobUrl();
  65661. };
  65662. }
  65663. catch (ex) {
  65664. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  65665. if (ex.code === 25) {
  65666. Database.IsUASupportingBlobStorage = false;
  65667. }
  65668. image.src = url;
  65669. }
  65670. }
  65671. else {
  65672. image.src = url;
  65673. }
  65674. }, false);
  65675. xhr.addEventListener("error", function (event) {
  65676. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  65677. image.src = url;
  65678. }, false);
  65679. xhr.send();
  65680. }
  65681. else {
  65682. image.src = url;
  65683. }
  65684. }
  65685. else {
  65686. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65687. image.src = url;
  65688. }
  65689. };
  65690. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  65691. var _this = this;
  65692. var updateVersion = function () {
  65693. // the version is not yet in the DB or we need to update it
  65694. _this._saveVersionIntoDBAsync(url, versionLoaded);
  65695. };
  65696. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  65697. };
  65698. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  65699. var _this = this;
  65700. if (this.isSupported && this.db) {
  65701. var version;
  65702. try {
  65703. var transaction = this.db.transaction(["versions"]);
  65704. transaction.oncomplete = function (event) {
  65705. if (version) {
  65706. // If the version in the JSON file is > than the version in DB
  65707. if (_this.manifestVersionFound > version.data) {
  65708. _this.mustUpdateRessources = true;
  65709. updateInDBCallback();
  65710. }
  65711. else {
  65712. callback(version.data);
  65713. }
  65714. }
  65715. else {
  65716. _this.mustUpdateRessources = true;
  65717. updateInDBCallback();
  65718. }
  65719. };
  65720. transaction.onabort = function (event) {
  65721. callback(-1);
  65722. };
  65723. var getRequest = transaction.objectStore("versions").get(url);
  65724. getRequest.onsuccess = function (event) {
  65725. version = (event.target).result;
  65726. };
  65727. getRequest.onerror = function (event) {
  65728. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  65729. callback(-1);
  65730. };
  65731. }
  65732. catch (ex) {
  65733. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  65734. callback(-1);
  65735. }
  65736. }
  65737. else {
  65738. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65739. callback(-1);
  65740. }
  65741. };
  65742. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  65743. var _this = this;
  65744. if (this.isSupported && !this.hasReachedQuota && this.db) {
  65745. try {
  65746. // Open a transaction to the database
  65747. var transaction = this.db.transaction(["versions"], "readwrite");
  65748. // the transaction could abort because of a QuotaExceededError error
  65749. transaction.onabort = function (event) {
  65750. try {
  65751. var error = event.srcElement['error'];
  65752. if (error && error.name === "QuotaExceededError") {
  65753. _this.hasReachedQuota = true;
  65754. }
  65755. }
  65756. catch (ex) { }
  65757. callback(-1);
  65758. };
  65759. transaction.oncomplete = function (event) {
  65760. callback(_this.manifestVersionFound);
  65761. };
  65762. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  65763. // Put the scene into the database
  65764. var addRequest = transaction.objectStore("versions").put(newVersion);
  65765. addRequest.onsuccess = function (event) {
  65766. };
  65767. addRequest.onerror = function (event) {
  65768. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  65769. };
  65770. }
  65771. catch (ex) {
  65772. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  65773. callback(-1);
  65774. }
  65775. }
  65776. else {
  65777. callback(-1);
  65778. }
  65779. };
  65780. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  65781. var _this = this;
  65782. var completeUrl = Database.ReturnFullUrlLocation(url);
  65783. var saveAndLoadFile = function () {
  65784. // the scene is not yet in the DB, let's try to save it
  65785. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  65786. };
  65787. this._checkVersionFromDB(completeUrl, function (version) {
  65788. if (version !== -1) {
  65789. if (!_this.mustUpdateRessources) {
  65790. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  65791. }
  65792. else {
  65793. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  65794. }
  65795. }
  65796. else {
  65797. if (errorCallback) {
  65798. errorCallback();
  65799. }
  65800. }
  65801. });
  65802. };
  65803. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  65804. if (this.isSupported && this.db) {
  65805. var targetStore;
  65806. if (url.indexOf(".babylon") !== -1) {
  65807. targetStore = "scenes";
  65808. }
  65809. else {
  65810. targetStore = "textures";
  65811. }
  65812. var file;
  65813. var transaction = this.db.transaction([targetStore]);
  65814. transaction.oncomplete = function (event) {
  65815. if (file) {
  65816. callback(file.data);
  65817. }
  65818. else {
  65819. notInDBCallback();
  65820. }
  65821. };
  65822. transaction.onabort = function (event) {
  65823. notInDBCallback();
  65824. };
  65825. var getRequest = transaction.objectStore(targetStore).get(url);
  65826. getRequest.onsuccess = function (event) {
  65827. file = (event.target).result;
  65828. };
  65829. getRequest.onerror = function (event) {
  65830. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  65831. notInDBCallback();
  65832. };
  65833. }
  65834. else {
  65835. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65836. callback();
  65837. }
  65838. };
  65839. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  65840. var _this = this;
  65841. if (this.isSupported) {
  65842. var targetStore;
  65843. if (url.indexOf(".babylon") !== -1) {
  65844. targetStore = "scenes";
  65845. }
  65846. else {
  65847. targetStore = "textures";
  65848. }
  65849. // Create XHR
  65850. var xhr = new XMLHttpRequest();
  65851. var fileData;
  65852. xhr.open("GET", url, true);
  65853. if (useArrayBuffer) {
  65854. xhr.responseType = "arraybuffer";
  65855. }
  65856. if (progressCallback) {
  65857. xhr.onprogress = progressCallback;
  65858. }
  65859. xhr.addEventListener("load", function () {
  65860. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  65861. // Blob as response (XHR2)
  65862. //fileData = xhr.responseText;
  65863. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  65864. if (!_this.hasReachedQuota && _this.db) {
  65865. // Open a transaction to the database
  65866. var transaction = _this.db.transaction([targetStore], "readwrite");
  65867. // the transaction could abort because of a QuotaExceededError error
  65868. transaction.onabort = function (event) {
  65869. try {
  65870. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  65871. var error = event.srcElement['error'];
  65872. if (error && error.name === "QuotaExceededError") {
  65873. _this.hasReachedQuota = true;
  65874. }
  65875. }
  65876. catch (ex) { }
  65877. callback(fileData);
  65878. };
  65879. transaction.oncomplete = function (event) {
  65880. callback(fileData);
  65881. };
  65882. var newFile;
  65883. if (targetStore === "scenes") {
  65884. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  65885. }
  65886. else {
  65887. newFile = { textureUrl: url, data: fileData };
  65888. }
  65889. try {
  65890. // Put the scene into the database
  65891. var addRequest = transaction.objectStore(targetStore).put(newFile);
  65892. addRequest.onsuccess = function (event) {
  65893. };
  65894. addRequest.onerror = function (event) {
  65895. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  65896. };
  65897. }
  65898. catch (ex) {
  65899. callback(fileData);
  65900. }
  65901. }
  65902. else {
  65903. callback(fileData);
  65904. }
  65905. }
  65906. else {
  65907. callback();
  65908. }
  65909. }, false);
  65910. xhr.addEventListener("error", function (event) {
  65911. BABYLON.Tools.Error("error on XHR request.");
  65912. callback();
  65913. }, false);
  65914. xhr.send();
  65915. }
  65916. else {
  65917. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65918. callback();
  65919. }
  65920. };
  65921. Database.IsUASupportingBlobStorage = true;
  65922. Database.IDBStorageEnabled = true;
  65923. Database.parseURL = function (url) {
  65924. var a = document.createElement('a');
  65925. a.href = url;
  65926. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  65927. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  65928. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  65929. return absLocation;
  65930. };
  65931. Database.ReturnFullUrlLocation = function (url) {
  65932. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  65933. return (Database.parseURL(window.location.href) + url);
  65934. }
  65935. else {
  65936. return url;
  65937. }
  65938. };
  65939. return Database;
  65940. }());
  65941. BABYLON.Database = Database;
  65942. })(BABYLON || (BABYLON = {}));
  65943. //# sourceMappingURL=babylon.database.js.map
  65944. "use strict";
  65945. var BABYLON;
  65946. (function (BABYLON) {
  65947. var FresnelParameters = /** @class */ (function () {
  65948. function FresnelParameters() {
  65949. this._isEnabled = true;
  65950. this.leftColor = BABYLON.Color3.White();
  65951. this.rightColor = BABYLON.Color3.Black();
  65952. this.bias = 0;
  65953. this.power = 1;
  65954. }
  65955. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  65956. get: function () {
  65957. return this._isEnabled;
  65958. },
  65959. set: function (value) {
  65960. if (this._isEnabled === value) {
  65961. return;
  65962. }
  65963. this._isEnabled = value;
  65964. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  65965. },
  65966. enumerable: true,
  65967. configurable: true
  65968. });
  65969. FresnelParameters.prototype.clone = function () {
  65970. var newFresnelParameters = new FresnelParameters();
  65971. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  65972. return newFresnelParameters;
  65973. };
  65974. FresnelParameters.prototype.serialize = function () {
  65975. var serializationObject = {};
  65976. serializationObject.isEnabled = this.isEnabled;
  65977. serializationObject.leftColor = this.leftColor.asArray();
  65978. serializationObject.rightColor = this.rightColor.asArray();
  65979. serializationObject.bias = this.bias;
  65980. serializationObject.power = this.power;
  65981. return serializationObject;
  65982. };
  65983. FresnelParameters.Parse = function (parsedFresnelParameters) {
  65984. var fresnelParameters = new FresnelParameters();
  65985. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  65986. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  65987. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  65988. fresnelParameters.bias = parsedFresnelParameters.bias;
  65989. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  65990. return fresnelParameters;
  65991. };
  65992. return FresnelParameters;
  65993. }());
  65994. BABYLON.FresnelParameters = FresnelParameters;
  65995. })(BABYLON || (BABYLON = {}));
  65996. //# sourceMappingURL=babylon.fresnelParameters.js.map
  65997. "use strict";
  65998. var BABYLON;
  65999. (function (BABYLON) {
  66000. var MultiMaterial = /** @class */ (function (_super) {
  66001. __extends(MultiMaterial, _super);
  66002. function MultiMaterial(name, scene) {
  66003. var _this = _super.call(this, name, scene, true) || this;
  66004. scene.multiMaterials.push(_this);
  66005. _this.subMaterials = new Array();
  66006. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  66007. return _this;
  66008. }
  66009. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  66010. get: function () {
  66011. return this._subMaterials;
  66012. },
  66013. set: function (value) {
  66014. this._subMaterials = value;
  66015. this._hookArray(value);
  66016. },
  66017. enumerable: true,
  66018. configurable: true
  66019. });
  66020. MultiMaterial.prototype._hookArray = function (array) {
  66021. var _this = this;
  66022. var oldPush = array.push;
  66023. array.push = function () {
  66024. var items = [];
  66025. for (var _i = 0; _i < arguments.length; _i++) {
  66026. items[_i] = arguments[_i];
  66027. }
  66028. var result = oldPush.apply(array, items);
  66029. _this._markAllSubMeshesAsTexturesDirty();
  66030. return result;
  66031. };
  66032. var oldSplice = array.splice;
  66033. array.splice = function (index, deleteCount) {
  66034. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66035. _this._markAllSubMeshesAsTexturesDirty();
  66036. return deleted;
  66037. };
  66038. };
  66039. // Properties
  66040. MultiMaterial.prototype.getSubMaterial = function (index) {
  66041. if (index < 0 || index >= this.subMaterials.length) {
  66042. return this.getScene().defaultMaterial;
  66043. }
  66044. return this.subMaterials[index];
  66045. };
  66046. MultiMaterial.prototype.getActiveTextures = function () {
  66047. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  66048. if (subMaterial) {
  66049. return subMaterial.getActiveTextures();
  66050. }
  66051. else {
  66052. return [];
  66053. }
  66054. }));
  66055. var _a;
  66056. };
  66057. // Methods
  66058. MultiMaterial.prototype.getClassName = function () {
  66059. return "MultiMaterial";
  66060. };
  66061. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  66062. for (var index = 0; index < this.subMaterials.length; index++) {
  66063. var subMaterial = this.subMaterials[index];
  66064. if (subMaterial) {
  66065. if (subMaterial.storeEffectOnSubMeshes) {
  66066. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  66067. return false;
  66068. }
  66069. continue;
  66070. }
  66071. if (!subMaterial.isReady(mesh)) {
  66072. return false;
  66073. }
  66074. }
  66075. }
  66076. return true;
  66077. };
  66078. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  66079. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  66080. for (var index = 0; index < this.subMaterials.length; index++) {
  66081. var subMaterial = null;
  66082. var current = this.subMaterials[index];
  66083. if (cloneChildren && current) {
  66084. subMaterial = current.clone(name + "-" + current.name);
  66085. }
  66086. else {
  66087. subMaterial = this.subMaterials[index];
  66088. }
  66089. newMultiMaterial.subMaterials.push(subMaterial);
  66090. }
  66091. return newMultiMaterial;
  66092. };
  66093. MultiMaterial.prototype.serialize = function () {
  66094. var serializationObject = {};
  66095. serializationObject.name = this.name;
  66096. serializationObject.id = this.id;
  66097. if (BABYLON.Tags) {
  66098. serializationObject.tags = BABYLON.Tags.GetTags(this);
  66099. }
  66100. serializationObject.materials = [];
  66101. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  66102. var subMat = this.subMaterials[matIndex];
  66103. if (subMat) {
  66104. serializationObject.materials.push(subMat.id);
  66105. }
  66106. else {
  66107. serializationObject.materials.push(null);
  66108. }
  66109. }
  66110. return serializationObject;
  66111. };
  66112. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  66113. var scene = this.getScene();
  66114. if (!scene) {
  66115. return;
  66116. }
  66117. var index = scene.multiMaterials.indexOf(this);
  66118. if (index >= 0) {
  66119. scene.multiMaterials.splice(index, 1);
  66120. }
  66121. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  66122. };
  66123. return MultiMaterial;
  66124. }(BABYLON.Material));
  66125. BABYLON.MultiMaterial = MultiMaterial;
  66126. })(BABYLON || (BABYLON = {}));
  66127. //# sourceMappingURL=babylon.multiMaterial.js.map
  66128. "use strict";
  66129. var BABYLON;
  66130. (function (BABYLON) {
  66131. var FreeCameraTouchInput = /** @class */ (function () {
  66132. function FreeCameraTouchInput() {
  66133. this._offsetX = null;
  66134. this._offsetY = null;
  66135. this._pointerPressed = new Array();
  66136. this.touchAngularSensibility = 200000.0;
  66137. this.touchMoveSensibility = 250.0;
  66138. }
  66139. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  66140. var _this = this;
  66141. var previousPosition = null;
  66142. if (this._pointerInput === undefined) {
  66143. this._onLostFocus = function (evt) {
  66144. _this._offsetX = null;
  66145. _this._offsetY = null;
  66146. };
  66147. this._pointerInput = function (p, s) {
  66148. var evt = p.event;
  66149. if (evt.pointerType === "mouse") {
  66150. return;
  66151. }
  66152. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  66153. if (!noPreventDefault) {
  66154. evt.preventDefault();
  66155. }
  66156. _this._pointerPressed.push(evt.pointerId);
  66157. if (_this._pointerPressed.length !== 1) {
  66158. return;
  66159. }
  66160. previousPosition = {
  66161. x: evt.clientX,
  66162. y: evt.clientY
  66163. };
  66164. }
  66165. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  66166. if (!noPreventDefault) {
  66167. evt.preventDefault();
  66168. }
  66169. var index = _this._pointerPressed.indexOf(evt.pointerId);
  66170. if (index === -1) {
  66171. return;
  66172. }
  66173. _this._pointerPressed.splice(index, 1);
  66174. if (index != 0) {
  66175. return;
  66176. }
  66177. previousPosition = null;
  66178. _this._offsetX = null;
  66179. _this._offsetY = null;
  66180. }
  66181. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  66182. if (!noPreventDefault) {
  66183. evt.preventDefault();
  66184. }
  66185. if (!previousPosition) {
  66186. return;
  66187. }
  66188. var index = _this._pointerPressed.indexOf(evt.pointerId);
  66189. if (index != 0) {
  66190. return;
  66191. }
  66192. _this._offsetX = evt.clientX - previousPosition.x;
  66193. _this._offsetY = -(evt.clientY - previousPosition.y);
  66194. }
  66195. };
  66196. }
  66197. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  66198. if (this._onLostFocus) {
  66199. element.addEventListener("blur", this._onLostFocus);
  66200. }
  66201. };
  66202. FreeCameraTouchInput.prototype.detachControl = function (element) {
  66203. if (this._pointerInput && element) {
  66204. if (this._observer) {
  66205. this.camera.getScene().onPointerObservable.remove(this._observer);
  66206. this._observer = null;
  66207. }
  66208. if (this._onLostFocus) {
  66209. element.removeEventListener("blur", this._onLostFocus);
  66210. this._onLostFocus = null;
  66211. }
  66212. this._pointerPressed = [];
  66213. this._offsetX = null;
  66214. this._offsetY = null;
  66215. }
  66216. };
  66217. FreeCameraTouchInput.prototype.checkInputs = function () {
  66218. if (this._offsetX && this._offsetY) {
  66219. var camera = this.camera;
  66220. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  66221. if (this._pointerPressed.length > 1) {
  66222. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  66223. }
  66224. else {
  66225. var speed = camera._computeLocalCameraSpeed();
  66226. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  66227. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  66228. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  66229. }
  66230. }
  66231. };
  66232. FreeCameraTouchInput.prototype.getClassName = function () {
  66233. return "FreeCameraTouchInput";
  66234. };
  66235. FreeCameraTouchInput.prototype.getSimpleName = function () {
  66236. return "touch";
  66237. };
  66238. __decorate([
  66239. BABYLON.serialize()
  66240. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  66241. __decorate([
  66242. BABYLON.serialize()
  66243. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  66244. return FreeCameraTouchInput;
  66245. }());
  66246. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  66247. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  66248. })(BABYLON || (BABYLON = {}));
  66249. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  66250. "use strict";
  66251. var BABYLON;
  66252. (function (BABYLON) {
  66253. // We're mainly based on the logic defined into the FreeCamera code
  66254. var TouchCamera = /** @class */ (function (_super) {
  66255. __extends(TouchCamera, _super);
  66256. //-- end properties for backward compatibility for inputs
  66257. function TouchCamera(name, position, scene) {
  66258. var _this = _super.call(this, name, position, scene) || this;
  66259. _this.inputs.addTouch();
  66260. _this._setupInputs();
  66261. return _this;
  66262. }
  66263. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  66264. //-- Begin properties for backward compatibility for inputs
  66265. get: function () {
  66266. var touch = this.inputs.attached["touch"];
  66267. if (touch)
  66268. return touch.touchAngularSensibility;
  66269. return 0;
  66270. },
  66271. set: function (value) {
  66272. var touch = this.inputs.attached["touch"];
  66273. if (touch)
  66274. touch.touchAngularSensibility = value;
  66275. },
  66276. enumerable: true,
  66277. configurable: true
  66278. });
  66279. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  66280. get: function () {
  66281. var touch = this.inputs.attached["touch"];
  66282. if (touch)
  66283. return touch.touchMoveSensibility;
  66284. return 0;
  66285. },
  66286. set: function (value) {
  66287. var touch = this.inputs.attached["touch"];
  66288. if (touch)
  66289. touch.touchMoveSensibility = value;
  66290. },
  66291. enumerable: true,
  66292. configurable: true
  66293. });
  66294. TouchCamera.prototype.getClassName = function () {
  66295. return "TouchCamera";
  66296. };
  66297. TouchCamera.prototype._setupInputs = function () {
  66298. var mouse = this.inputs.attached["mouse"];
  66299. if (mouse) {
  66300. mouse.touchEnabled = false;
  66301. }
  66302. };
  66303. return TouchCamera;
  66304. }(BABYLON.FreeCamera));
  66305. BABYLON.TouchCamera = TouchCamera;
  66306. })(BABYLON || (BABYLON = {}));
  66307. //# sourceMappingURL=babylon.touchCamera.js.map
  66308. "use strict";
  66309. var BABYLON;
  66310. (function (BABYLON) {
  66311. var ProceduralTexture = /** @class */ (function (_super) {
  66312. __extends(ProceduralTexture, _super);
  66313. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  66314. if (fallbackTexture === void 0) { fallbackTexture = null; }
  66315. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66316. if (isCube === void 0) { isCube = false; }
  66317. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66318. _this.isCube = isCube;
  66319. _this.isEnabled = true;
  66320. _this._currentRefreshId = -1;
  66321. _this._refreshRate = 1;
  66322. _this._vertexBuffers = {};
  66323. _this._uniforms = new Array();
  66324. _this._samplers = new Array();
  66325. _this._textures = {};
  66326. _this._floats = {};
  66327. _this._floatsArrays = {};
  66328. _this._colors3 = {};
  66329. _this._colors4 = {};
  66330. _this._vectors2 = {};
  66331. _this._vectors3 = {};
  66332. _this._matrices = {};
  66333. _this._fallbackTextureUsed = false;
  66334. scene.proceduralTextures.push(_this);
  66335. _this._engine = scene.getEngine();
  66336. _this.name = name;
  66337. _this.isRenderTarget = true;
  66338. _this._size = size;
  66339. _this._generateMipMaps = generateMipMaps;
  66340. _this.setFragment(fragment);
  66341. _this._fallbackTexture = fallbackTexture;
  66342. if (isCube) {
  66343. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  66344. _this.setFloat("face", 0);
  66345. }
  66346. else {
  66347. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  66348. }
  66349. // VBO
  66350. var vertices = [];
  66351. vertices.push(1, 1);
  66352. vertices.push(-1, 1);
  66353. vertices.push(-1, -1);
  66354. vertices.push(1, -1);
  66355. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66356. _this._createIndexBuffer();
  66357. return _this;
  66358. }
  66359. ProceduralTexture.prototype._createIndexBuffer = function () {
  66360. var engine = this._engine;
  66361. // Indices
  66362. var indices = [];
  66363. indices.push(0);
  66364. indices.push(1);
  66365. indices.push(2);
  66366. indices.push(0);
  66367. indices.push(2);
  66368. indices.push(3);
  66369. this._indexBuffer = engine.createIndexBuffer(indices);
  66370. };
  66371. ProceduralTexture.prototype._rebuild = function () {
  66372. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66373. if (vb) {
  66374. vb._rebuild();
  66375. }
  66376. this._createIndexBuffer();
  66377. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  66378. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  66379. }
  66380. };
  66381. ProceduralTexture.prototype.reset = function () {
  66382. if (this._effect === undefined) {
  66383. return;
  66384. }
  66385. var engine = this._engine;
  66386. engine._releaseEffect(this._effect);
  66387. };
  66388. ProceduralTexture.prototype.isReady = function () {
  66389. var _this = this;
  66390. var engine = this._engine;
  66391. var shaders;
  66392. if (!this._fragment) {
  66393. return false;
  66394. }
  66395. if (this._fallbackTextureUsed) {
  66396. return true;
  66397. }
  66398. if (this._fragment.fragmentElement !== undefined) {
  66399. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  66400. }
  66401. else {
  66402. shaders = { vertex: "procedural", fragment: this._fragment };
  66403. }
  66404. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  66405. _this.releaseInternalTexture();
  66406. if (_this._fallbackTexture) {
  66407. _this._texture = _this._fallbackTexture._texture;
  66408. if (_this._texture) {
  66409. _this._texture.incrementReferences();
  66410. }
  66411. }
  66412. _this._fallbackTextureUsed = true;
  66413. });
  66414. return this._effect.isReady();
  66415. };
  66416. ProceduralTexture.prototype.resetRefreshCounter = function () {
  66417. this._currentRefreshId = -1;
  66418. };
  66419. ProceduralTexture.prototype.setFragment = function (fragment) {
  66420. this._fragment = fragment;
  66421. };
  66422. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  66423. get: function () {
  66424. return this._refreshRate;
  66425. },
  66426. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66427. set: function (value) {
  66428. this._refreshRate = value;
  66429. this.resetRefreshCounter();
  66430. },
  66431. enumerable: true,
  66432. configurable: true
  66433. });
  66434. ProceduralTexture.prototype._shouldRender = function () {
  66435. if (!this.isEnabled || !this.isReady() || !this._texture) {
  66436. return false;
  66437. }
  66438. if (this._fallbackTextureUsed) {
  66439. return false;
  66440. }
  66441. if (this._currentRefreshId === -1) {
  66442. this._currentRefreshId = 1;
  66443. return true;
  66444. }
  66445. if (this.refreshRate === this._currentRefreshId) {
  66446. this._currentRefreshId = 1;
  66447. return true;
  66448. }
  66449. this._currentRefreshId++;
  66450. return false;
  66451. };
  66452. ProceduralTexture.prototype.getRenderSize = function () {
  66453. return this._size;
  66454. };
  66455. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  66456. if (this._fallbackTextureUsed) {
  66457. return;
  66458. }
  66459. this.releaseInternalTexture();
  66460. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  66461. };
  66462. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  66463. if (this._uniforms.indexOf(uniformName) === -1) {
  66464. this._uniforms.push(uniformName);
  66465. }
  66466. };
  66467. ProceduralTexture.prototype.setTexture = function (name, texture) {
  66468. if (this._samplers.indexOf(name) === -1) {
  66469. this._samplers.push(name);
  66470. }
  66471. this._textures[name] = texture;
  66472. return this;
  66473. };
  66474. ProceduralTexture.prototype.setFloat = function (name, value) {
  66475. this._checkUniform(name);
  66476. this._floats[name] = value;
  66477. return this;
  66478. };
  66479. ProceduralTexture.prototype.setFloats = function (name, value) {
  66480. this._checkUniform(name);
  66481. this._floatsArrays[name] = value;
  66482. return this;
  66483. };
  66484. ProceduralTexture.prototype.setColor3 = function (name, value) {
  66485. this._checkUniform(name);
  66486. this._colors3[name] = value;
  66487. return this;
  66488. };
  66489. ProceduralTexture.prototype.setColor4 = function (name, value) {
  66490. this._checkUniform(name);
  66491. this._colors4[name] = value;
  66492. return this;
  66493. };
  66494. ProceduralTexture.prototype.setVector2 = function (name, value) {
  66495. this._checkUniform(name);
  66496. this._vectors2[name] = value;
  66497. return this;
  66498. };
  66499. ProceduralTexture.prototype.setVector3 = function (name, value) {
  66500. this._checkUniform(name);
  66501. this._vectors3[name] = value;
  66502. return this;
  66503. };
  66504. ProceduralTexture.prototype.setMatrix = function (name, value) {
  66505. this._checkUniform(name);
  66506. this._matrices[name] = value;
  66507. return this;
  66508. };
  66509. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  66510. var scene = this.getScene();
  66511. if (!scene) {
  66512. return;
  66513. }
  66514. var engine = this._engine;
  66515. // Render
  66516. engine.enableEffect(this._effect);
  66517. engine.setState(false);
  66518. // Texture
  66519. for (var name in this._textures) {
  66520. this._effect.setTexture(name, this._textures[name]);
  66521. }
  66522. // Float
  66523. for (name in this._floats) {
  66524. this._effect.setFloat(name, this._floats[name]);
  66525. }
  66526. // Floats
  66527. for (name in this._floatsArrays) {
  66528. this._effect.setArray(name, this._floatsArrays[name]);
  66529. }
  66530. // Color3
  66531. for (name in this._colors3) {
  66532. this._effect.setColor3(name, this._colors3[name]);
  66533. }
  66534. // Color4
  66535. for (name in this._colors4) {
  66536. var color = this._colors4[name];
  66537. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  66538. }
  66539. // Vector2
  66540. for (name in this._vectors2) {
  66541. this._effect.setVector2(name, this._vectors2[name]);
  66542. }
  66543. // Vector3
  66544. for (name in this._vectors3) {
  66545. this._effect.setVector3(name, this._vectors3[name]);
  66546. }
  66547. // Matrix
  66548. for (name in this._matrices) {
  66549. this._effect.setMatrix(name, this._matrices[name]);
  66550. }
  66551. if (!this._texture) {
  66552. return;
  66553. }
  66554. if (this.isCube) {
  66555. for (var face = 0; face < 6; face++) {
  66556. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  66557. // VBOs
  66558. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66559. this._effect.setFloat("face", face);
  66560. // Clear
  66561. engine.clear(scene.clearColor, true, true, true);
  66562. // Draw order
  66563. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66564. // Mipmaps
  66565. if (face === 5) {
  66566. engine.generateMipMapsForCubemap(this._texture);
  66567. }
  66568. }
  66569. }
  66570. else {
  66571. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  66572. // VBOs
  66573. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66574. // Clear
  66575. engine.clear(scene.clearColor, true, true, true);
  66576. // Draw order
  66577. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66578. }
  66579. // Unbind
  66580. engine.unBindFramebuffer(this._texture, this.isCube);
  66581. if (this.onGenerated) {
  66582. this.onGenerated();
  66583. }
  66584. };
  66585. ProceduralTexture.prototype.clone = function () {
  66586. var textureSize = this.getSize();
  66587. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  66588. // Base texture
  66589. newTexture.hasAlpha = this.hasAlpha;
  66590. newTexture.level = this.level;
  66591. // RenderTarget Texture
  66592. newTexture.coordinatesMode = this.coordinatesMode;
  66593. return newTexture;
  66594. };
  66595. ProceduralTexture.prototype.dispose = function () {
  66596. var scene = this.getScene();
  66597. if (!scene) {
  66598. return;
  66599. }
  66600. var index = scene.proceduralTextures.indexOf(this);
  66601. if (index >= 0) {
  66602. scene.proceduralTextures.splice(index, 1);
  66603. }
  66604. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66605. if (vertexBuffer) {
  66606. vertexBuffer.dispose();
  66607. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66608. }
  66609. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  66610. this._indexBuffer = null;
  66611. }
  66612. _super.prototype.dispose.call(this);
  66613. };
  66614. return ProceduralTexture;
  66615. }(BABYLON.Texture));
  66616. BABYLON.ProceduralTexture = ProceduralTexture;
  66617. })(BABYLON || (BABYLON = {}));
  66618. //# sourceMappingURL=babylon.proceduralTexture.js.map
  66619. "use strict";
  66620. var BABYLON;
  66621. (function (BABYLON) {
  66622. var CustomProceduralTexture = /** @class */ (function (_super) {
  66623. __extends(CustomProceduralTexture, _super);
  66624. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  66625. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  66626. _this._animate = true;
  66627. _this._time = 0;
  66628. _this._texturePath = texturePath;
  66629. //Try to load json
  66630. _this.loadJson(texturePath);
  66631. _this.refreshRate = 1;
  66632. return _this;
  66633. }
  66634. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  66635. var _this = this;
  66636. var noConfigFile = function () {
  66637. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  66638. try {
  66639. _this.setFragment(_this._texturePath);
  66640. }
  66641. catch (ex) {
  66642. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  66643. }
  66644. };
  66645. var configFileUrl = jsonUrl + "/config.json";
  66646. var xhr = new XMLHttpRequest();
  66647. xhr.open("GET", configFileUrl, true);
  66648. xhr.addEventListener("load", function () {
  66649. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  66650. try {
  66651. _this._config = JSON.parse(xhr.response);
  66652. _this.updateShaderUniforms();
  66653. _this.updateTextures();
  66654. _this.setFragment(_this._texturePath + "/custom");
  66655. _this._animate = _this._config.animate;
  66656. _this.refreshRate = _this._config.refreshrate;
  66657. }
  66658. catch (ex) {
  66659. noConfigFile();
  66660. }
  66661. }
  66662. else {
  66663. noConfigFile();
  66664. }
  66665. }, false);
  66666. xhr.addEventListener("error", function () {
  66667. noConfigFile();
  66668. }, false);
  66669. try {
  66670. xhr.send();
  66671. }
  66672. catch (ex) {
  66673. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  66674. }
  66675. };
  66676. CustomProceduralTexture.prototype.isReady = function () {
  66677. if (!_super.prototype.isReady.call(this)) {
  66678. return false;
  66679. }
  66680. for (var name in this._textures) {
  66681. var texture = this._textures[name];
  66682. if (!texture.isReady()) {
  66683. return false;
  66684. }
  66685. }
  66686. return true;
  66687. };
  66688. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  66689. var scene = this.getScene();
  66690. if (this._animate && scene) {
  66691. this._time += scene.getAnimationRatio() * 0.03;
  66692. this.updateShaderUniforms();
  66693. }
  66694. _super.prototype.render.call(this, useCameraPostProcess);
  66695. };
  66696. CustomProceduralTexture.prototype.updateTextures = function () {
  66697. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  66698. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  66699. }
  66700. };
  66701. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  66702. if (this._config) {
  66703. for (var j = 0; j < this._config.uniforms.length; j++) {
  66704. var uniform = this._config.uniforms[j];
  66705. switch (uniform.type) {
  66706. case "float":
  66707. this.setFloat(uniform.name, uniform.value);
  66708. break;
  66709. case "color3":
  66710. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  66711. break;
  66712. case "color4":
  66713. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  66714. break;
  66715. case "vector2":
  66716. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  66717. break;
  66718. case "vector3":
  66719. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  66720. break;
  66721. }
  66722. }
  66723. }
  66724. this.setFloat("time", this._time);
  66725. };
  66726. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  66727. get: function () {
  66728. return this._animate;
  66729. },
  66730. set: function (value) {
  66731. this._animate = value;
  66732. },
  66733. enumerable: true,
  66734. configurable: true
  66735. });
  66736. return CustomProceduralTexture;
  66737. }(BABYLON.ProceduralTexture));
  66738. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  66739. })(BABYLON || (BABYLON = {}));
  66740. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  66741. "use strict";
  66742. var BABYLON;
  66743. (function (BABYLON) {
  66744. var FreeCameraGamepadInput = /** @class */ (function () {
  66745. function FreeCameraGamepadInput() {
  66746. this.gamepadAngularSensibility = 200;
  66747. this.gamepadMoveSensibility = 40;
  66748. // private members
  66749. this._cameraTransform = BABYLON.Matrix.Identity();
  66750. this._deltaTransform = BABYLON.Vector3.Zero();
  66751. this._vector3 = BABYLON.Vector3.Zero();
  66752. this._vector2 = BABYLON.Vector2.Zero();
  66753. }
  66754. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  66755. var _this = this;
  66756. var manager = this.camera.getScene().gamepadManager;
  66757. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66758. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  66759. // prioritize XBOX gamepads.
  66760. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  66761. _this.gamepad = gamepad;
  66762. }
  66763. }
  66764. });
  66765. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66766. if (_this.gamepad === gamepad) {
  66767. _this.gamepad = null;
  66768. }
  66769. });
  66770. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  66771. };
  66772. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  66773. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66774. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66775. this.gamepad = null;
  66776. };
  66777. FreeCameraGamepadInput.prototype.checkInputs = function () {
  66778. if (this.gamepad && this.gamepad.leftStick) {
  66779. var camera = this.camera;
  66780. var LSValues = this.gamepad.leftStick;
  66781. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  66782. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  66783. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  66784. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  66785. var RSValues = this.gamepad.rightStick;
  66786. if (RSValues) {
  66787. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  66788. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  66789. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  66790. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  66791. }
  66792. else {
  66793. RSValues = { x: 0, y: 0 };
  66794. }
  66795. if (!camera.rotationQuaternion) {
  66796. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  66797. }
  66798. else {
  66799. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  66800. }
  66801. var speed = camera._computeLocalCameraSpeed() * 50.0;
  66802. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  66803. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  66804. camera.cameraDirection.addInPlace(this._deltaTransform);
  66805. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  66806. camera.cameraRotation.addInPlace(this._vector2);
  66807. }
  66808. };
  66809. FreeCameraGamepadInput.prototype.getClassName = function () {
  66810. return "FreeCameraGamepadInput";
  66811. };
  66812. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  66813. return "gamepad";
  66814. };
  66815. __decorate([
  66816. BABYLON.serialize()
  66817. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  66818. __decorate([
  66819. BABYLON.serialize()
  66820. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  66821. return FreeCameraGamepadInput;
  66822. }());
  66823. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  66824. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  66825. })(BABYLON || (BABYLON = {}));
  66826. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  66827. "use strict";
  66828. var BABYLON;
  66829. (function (BABYLON) {
  66830. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  66831. function ArcRotateCameraGamepadInput() {
  66832. this.gamepadRotationSensibility = 80;
  66833. this.gamepadMoveSensibility = 40;
  66834. }
  66835. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  66836. var _this = this;
  66837. var manager = this.camera.getScene().gamepadManager;
  66838. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66839. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  66840. // prioritize XBOX gamepads.
  66841. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  66842. _this.gamepad = gamepad;
  66843. }
  66844. }
  66845. });
  66846. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66847. if (_this.gamepad === gamepad) {
  66848. _this.gamepad = null;
  66849. }
  66850. });
  66851. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  66852. };
  66853. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  66854. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66855. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66856. this.gamepad = null;
  66857. };
  66858. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  66859. if (this.gamepad) {
  66860. var camera = this.camera;
  66861. var RSValues = this.gamepad.rightStick;
  66862. if (RSValues) {
  66863. if (RSValues.x != 0) {
  66864. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  66865. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  66866. camera.inertialAlphaOffset += normalizedRX;
  66867. }
  66868. }
  66869. if (RSValues.y != 0) {
  66870. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  66871. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  66872. camera.inertialBetaOffset += normalizedRY;
  66873. }
  66874. }
  66875. }
  66876. var LSValues = this.gamepad.leftStick;
  66877. if (LSValues && LSValues.y != 0) {
  66878. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  66879. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  66880. this.camera.inertialRadiusOffset -= normalizedLY;
  66881. }
  66882. }
  66883. }
  66884. };
  66885. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  66886. return "ArcRotateCameraGamepadInput";
  66887. };
  66888. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  66889. return "gamepad";
  66890. };
  66891. __decorate([
  66892. BABYLON.serialize()
  66893. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  66894. __decorate([
  66895. BABYLON.serialize()
  66896. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  66897. return ArcRotateCameraGamepadInput;
  66898. }());
  66899. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  66900. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  66901. })(BABYLON || (BABYLON = {}));
  66902. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  66903. "use strict";
  66904. var BABYLON;
  66905. (function (BABYLON) {
  66906. var GamepadManager = /** @class */ (function () {
  66907. function GamepadManager(_scene) {
  66908. var _this = this;
  66909. this._scene = _scene;
  66910. this._babylonGamepads = [];
  66911. this._oneGamepadConnected = false;
  66912. this._isMonitoring = false;
  66913. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  66914. if (!BABYLON.Tools.IsWindowObjectExist()) {
  66915. this._gamepadEventSupported = false;
  66916. }
  66917. else {
  66918. this._gamepadEventSupported = 'GamepadEvent' in window;
  66919. this._gamepadSupport = (navigator.getGamepads ||
  66920. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  66921. }
  66922. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  66923. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  66924. for (var i in _this._babylonGamepads) {
  66925. var gamepad = _this._babylonGamepads[i];
  66926. if (gamepad && gamepad._isConnected) {
  66927. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  66928. }
  66929. }
  66930. });
  66931. this._onGamepadConnectedEvent = function (evt) {
  66932. var gamepad = evt.gamepad;
  66933. if (gamepad.index in _this._babylonGamepads) {
  66934. if (_this._babylonGamepads[gamepad.index].isConnected) {
  66935. return;
  66936. }
  66937. }
  66938. var newGamepad;
  66939. if (_this._babylonGamepads[gamepad.index]) {
  66940. newGamepad = _this._babylonGamepads[gamepad.index];
  66941. newGamepad.browserGamepad = gamepad;
  66942. newGamepad._isConnected = true;
  66943. }
  66944. else {
  66945. newGamepad = _this._addNewGamepad(gamepad);
  66946. }
  66947. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66948. _this._startMonitoringGamepads();
  66949. };
  66950. this._onGamepadDisconnectedEvent = function (evt) {
  66951. var gamepad = evt.gamepad;
  66952. // Remove the gamepad from the list of gamepads to monitor.
  66953. for (var i in _this._babylonGamepads) {
  66954. if (_this._babylonGamepads[i].index === gamepad.index) {
  66955. var disconnectedGamepad = _this._babylonGamepads[i];
  66956. disconnectedGamepad._isConnected = false;
  66957. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  66958. break;
  66959. }
  66960. }
  66961. };
  66962. if (this._gamepadSupport) {
  66963. //first add already-connected gamepads
  66964. this._updateGamepadObjects();
  66965. if (this._babylonGamepads.length) {
  66966. this._startMonitoringGamepads();
  66967. }
  66968. // Checking if the gamepad connected event is supported (like in Firefox)
  66969. if (this._gamepadEventSupported) {
  66970. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  66971. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  66972. }
  66973. else {
  66974. this._startMonitoringGamepads();
  66975. }
  66976. }
  66977. }
  66978. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  66979. get: function () {
  66980. return this._babylonGamepads;
  66981. },
  66982. enumerable: true,
  66983. configurable: true
  66984. });
  66985. GamepadManager.prototype.getGamepadByType = function (type) {
  66986. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  66987. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  66988. var gamepad = _a[_i];
  66989. if (gamepad && gamepad.type === type) {
  66990. return gamepad;
  66991. }
  66992. }
  66993. return null;
  66994. };
  66995. GamepadManager.prototype.dispose = function () {
  66996. if (this._gamepadEventSupported) {
  66997. if (this._onGamepadConnectedEvent) {
  66998. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  66999. }
  67000. if (this._onGamepadDisconnectedEvent) {
  67001. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  67002. }
  67003. this._onGamepadConnectedEvent = null;
  67004. this._onGamepadDisconnectedEvent = null;
  67005. }
  67006. this._babylonGamepads.forEach(function (gamepad) {
  67007. gamepad.dispose();
  67008. });
  67009. this.onGamepadConnectedObservable.clear();
  67010. this.onGamepadDisconnectedObservable.clear();
  67011. this._oneGamepadConnected = false;
  67012. this._stopMonitoringGamepads();
  67013. this._babylonGamepads = [];
  67014. };
  67015. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  67016. if (!this._oneGamepadConnected) {
  67017. this._oneGamepadConnected = true;
  67018. }
  67019. var newGamepad;
  67020. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  67021. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  67022. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  67023. }
  67024. else if (gamepad.pose) {
  67025. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  67026. }
  67027. else {
  67028. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  67029. }
  67030. this._babylonGamepads[newGamepad.index] = newGamepad;
  67031. return newGamepad;
  67032. };
  67033. GamepadManager.prototype._startMonitoringGamepads = function () {
  67034. if (!this._isMonitoring) {
  67035. this._isMonitoring = true;
  67036. //back-comp
  67037. if (!this._scene) {
  67038. this._checkGamepadsStatus();
  67039. }
  67040. }
  67041. };
  67042. GamepadManager.prototype._stopMonitoringGamepads = function () {
  67043. this._isMonitoring = false;
  67044. };
  67045. GamepadManager.prototype._checkGamepadsStatus = function () {
  67046. var _this = this;
  67047. // Hack to be compatible Chrome
  67048. this._updateGamepadObjects();
  67049. for (var i in this._babylonGamepads) {
  67050. var gamepad = this._babylonGamepads[i];
  67051. if (!gamepad || !gamepad.isConnected) {
  67052. continue;
  67053. }
  67054. gamepad.update();
  67055. }
  67056. if (this._isMonitoring && !this._scene) {
  67057. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  67058. }
  67059. };
  67060. // This function is called only on Chrome, which does not properly support
  67061. // connection/disconnection events and forces you to recopy again the gamepad object
  67062. GamepadManager.prototype._updateGamepadObjects = function () {
  67063. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  67064. for (var i = 0; i < gamepads.length; i++) {
  67065. if (gamepads[i]) {
  67066. if (!this._babylonGamepads[gamepads[i].index]) {
  67067. var newGamepad = this._addNewGamepad(gamepads[i]);
  67068. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  67069. }
  67070. else {
  67071. // Forced to copy again this object for Chrome for unknown reason
  67072. this._babylonGamepads[i].browserGamepad = gamepads[i];
  67073. if (!this._babylonGamepads[i].isConnected) {
  67074. this._babylonGamepads[i]._isConnected = true;
  67075. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  67076. }
  67077. }
  67078. }
  67079. }
  67080. };
  67081. return GamepadManager;
  67082. }());
  67083. BABYLON.GamepadManager = GamepadManager;
  67084. })(BABYLON || (BABYLON = {}));
  67085. //# sourceMappingURL=babylon.gamepadManager.js.map
  67086. "use strict";
  67087. var BABYLON;
  67088. (function (BABYLON) {
  67089. var StickValues = /** @class */ (function () {
  67090. function StickValues(x, y) {
  67091. this.x = x;
  67092. this.y = y;
  67093. }
  67094. return StickValues;
  67095. }());
  67096. BABYLON.StickValues = StickValues;
  67097. var Gamepad = /** @class */ (function () {
  67098. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  67099. if (leftStickX === void 0) { leftStickX = 0; }
  67100. if (leftStickY === void 0) { leftStickY = 1; }
  67101. if (rightStickX === void 0) { rightStickX = 2; }
  67102. if (rightStickY === void 0) { rightStickY = 3; }
  67103. this.id = id;
  67104. this.index = index;
  67105. this.browserGamepad = browserGamepad;
  67106. this._isConnected = true;
  67107. this._invertLeftStickY = false;
  67108. this.type = Gamepad.GAMEPAD;
  67109. this._leftStickAxisX = leftStickX;
  67110. this._leftStickAxisY = leftStickY;
  67111. this._rightStickAxisX = rightStickX;
  67112. this._rightStickAxisY = rightStickY;
  67113. if (this.browserGamepad.axes.length >= 2) {
  67114. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  67115. }
  67116. if (this.browserGamepad.axes.length >= 4) {
  67117. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  67118. }
  67119. }
  67120. Object.defineProperty(Gamepad.prototype, "isConnected", {
  67121. get: function () {
  67122. return this._isConnected;
  67123. },
  67124. enumerable: true,
  67125. configurable: true
  67126. });
  67127. Gamepad.prototype.onleftstickchanged = function (callback) {
  67128. this._onleftstickchanged = callback;
  67129. };
  67130. Gamepad.prototype.onrightstickchanged = function (callback) {
  67131. this._onrightstickchanged = callback;
  67132. };
  67133. Object.defineProperty(Gamepad.prototype, "leftStick", {
  67134. get: function () {
  67135. return this._leftStick;
  67136. },
  67137. set: function (newValues) {
  67138. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  67139. this._onleftstickchanged(newValues);
  67140. }
  67141. this._leftStick = newValues;
  67142. },
  67143. enumerable: true,
  67144. configurable: true
  67145. });
  67146. Object.defineProperty(Gamepad.prototype, "rightStick", {
  67147. get: function () {
  67148. return this._rightStick;
  67149. },
  67150. set: function (newValues) {
  67151. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  67152. this._onrightstickchanged(newValues);
  67153. }
  67154. this._rightStick = newValues;
  67155. },
  67156. enumerable: true,
  67157. configurable: true
  67158. });
  67159. Gamepad.prototype.update = function () {
  67160. if (this._leftStick) {
  67161. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  67162. if (this._invertLeftStickY) {
  67163. this.leftStick.y *= -1;
  67164. }
  67165. }
  67166. if (this._rightStick) {
  67167. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  67168. }
  67169. };
  67170. Gamepad.prototype.dispose = function () {
  67171. };
  67172. Gamepad.GAMEPAD = 0;
  67173. Gamepad.GENERIC = 1;
  67174. Gamepad.XBOX = 2;
  67175. Gamepad.POSE_ENABLED = 3;
  67176. return Gamepad;
  67177. }());
  67178. BABYLON.Gamepad = Gamepad;
  67179. var GenericPad = /** @class */ (function (_super) {
  67180. __extends(GenericPad, _super);
  67181. function GenericPad(id, index, browserGamepad) {
  67182. var _this = _super.call(this, id, index, browserGamepad) || this;
  67183. _this.onButtonDownObservable = new BABYLON.Observable();
  67184. _this.onButtonUpObservable = new BABYLON.Observable();
  67185. _this.type = Gamepad.GENERIC;
  67186. _this._buttons = new Array(browserGamepad.buttons.length);
  67187. return _this;
  67188. }
  67189. GenericPad.prototype.onbuttondown = function (callback) {
  67190. this._onbuttondown = callback;
  67191. };
  67192. GenericPad.prototype.onbuttonup = function (callback) {
  67193. this._onbuttonup = callback;
  67194. };
  67195. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  67196. if (newValue !== currentValue) {
  67197. if (newValue === 1) {
  67198. if (this._onbuttondown) {
  67199. this._onbuttondown(buttonIndex);
  67200. }
  67201. this.onButtonDownObservable.notifyObservers(buttonIndex);
  67202. }
  67203. if (newValue === 0) {
  67204. if (this._onbuttonup) {
  67205. this._onbuttonup(buttonIndex);
  67206. }
  67207. this.onButtonUpObservable.notifyObservers(buttonIndex);
  67208. }
  67209. }
  67210. return newValue;
  67211. };
  67212. GenericPad.prototype.update = function () {
  67213. _super.prototype.update.call(this);
  67214. for (var index = 0; index < this._buttons.length; index++) {
  67215. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  67216. }
  67217. };
  67218. GenericPad.prototype.dispose = function () {
  67219. _super.prototype.dispose.call(this);
  67220. this.onButtonDownObservable.clear();
  67221. this.onButtonUpObservable.clear();
  67222. };
  67223. return GenericPad;
  67224. }(Gamepad));
  67225. BABYLON.GenericPad = GenericPad;
  67226. })(BABYLON || (BABYLON = {}));
  67227. //# sourceMappingURL=babylon.gamepad.js.map
  67228. "use strict";
  67229. var BABYLON;
  67230. (function (BABYLON) {
  67231. var Xbox360Button;
  67232. (function (Xbox360Button) {
  67233. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  67234. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  67235. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  67236. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  67237. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  67238. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  67239. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  67240. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  67241. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  67242. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  67243. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  67244. var Xbox360Dpad;
  67245. (function (Xbox360Dpad) {
  67246. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  67247. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  67248. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  67249. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  67250. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  67251. var Xbox360Pad = /** @class */ (function (_super) {
  67252. __extends(Xbox360Pad, _super);
  67253. function Xbox360Pad(id, index, gamepad, xboxOne) {
  67254. if (xboxOne === void 0) { xboxOne = false; }
  67255. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  67256. _this._leftTrigger = 0;
  67257. _this._rightTrigger = 0;
  67258. _this.onButtonDownObservable = new BABYLON.Observable();
  67259. _this.onButtonUpObservable = new BABYLON.Observable();
  67260. _this.onPadDownObservable = new BABYLON.Observable();
  67261. _this.onPadUpObservable = new BABYLON.Observable();
  67262. _this._buttonA = 0;
  67263. _this._buttonB = 0;
  67264. _this._buttonX = 0;
  67265. _this._buttonY = 0;
  67266. _this._buttonBack = 0;
  67267. _this._buttonStart = 0;
  67268. _this._buttonLB = 0;
  67269. _this._buttonRB = 0;
  67270. _this._buttonLeftStick = 0;
  67271. _this._buttonRightStick = 0;
  67272. _this._dPadUp = 0;
  67273. _this._dPadDown = 0;
  67274. _this._dPadLeft = 0;
  67275. _this._dPadRight = 0;
  67276. _this._isXboxOnePad = false;
  67277. _this.type = BABYLON.Gamepad.XBOX;
  67278. _this._isXboxOnePad = xboxOne;
  67279. return _this;
  67280. }
  67281. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  67282. this._onlefttriggerchanged = callback;
  67283. };
  67284. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  67285. this._onrighttriggerchanged = callback;
  67286. };
  67287. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  67288. get: function () {
  67289. return this._leftTrigger;
  67290. },
  67291. set: function (newValue) {
  67292. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  67293. this._onlefttriggerchanged(newValue);
  67294. }
  67295. this._leftTrigger = newValue;
  67296. },
  67297. enumerable: true,
  67298. configurable: true
  67299. });
  67300. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  67301. get: function () {
  67302. return this._rightTrigger;
  67303. },
  67304. set: function (newValue) {
  67305. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  67306. this._onrighttriggerchanged(newValue);
  67307. }
  67308. this._rightTrigger = newValue;
  67309. },
  67310. enumerable: true,
  67311. configurable: true
  67312. });
  67313. Xbox360Pad.prototype.onbuttondown = function (callback) {
  67314. this._onbuttondown = callback;
  67315. };
  67316. Xbox360Pad.prototype.onbuttonup = function (callback) {
  67317. this._onbuttonup = callback;
  67318. };
  67319. Xbox360Pad.prototype.ondpaddown = function (callback) {
  67320. this._ondpaddown = callback;
  67321. };
  67322. Xbox360Pad.prototype.ondpadup = function (callback) {
  67323. this._ondpadup = callback;
  67324. };
  67325. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  67326. if (newValue !== currentValue) {
  67327. if (newValue === 1) {
  67328. if (this._onbuttondown) {
  67329. this._onbuttondown(buttonType);
  67330. }
  67331. this.onButtonDownObservable.notifyObservers(buttonType);
  67332. }
  67333. if (newValue === 0) {
  67334. if (this._onbuttonup) {
  67335. this._onbuttonup(buttonType);
  67336. }
  67337. this.onButtonUpObservable.notifyObservers(buttonType);
  67338. }
  67339. }
  67340. return newValue;
  67341. };
  67342. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  67343. if (newValue !== currentValue) {
  67344. if (newValue === 1) {
  67345. if (this._ondpaddown) {
  67346. this._ondpaddown(buttonType);
  67347. }
  67348. this.onPadDownObservable.notifyObservers(buttonType);
  67349. }
  67350. if (newValue === 0) {
  67351. if (this._ondpadup) {
  67352. this._ondpadup(buttonType);
  67353. }
  67354. this.onPadUpObservable.notifyObservers(buttonType);
  67355. }
  67356. }
  67357. return newValue;
  67358. };
  67359. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  67360. get: function () {
  67361. return this._buttonA;
  67362. },
  67363. set: function (value) {
  67364. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  67365. },
  67366. enumerable: true,
  67367. configurable: true
  67368. });
  67369. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  67370. get: function () {
  67371. return this._buttonB;
  67372. },
  67373. set: function (value) {
  67374. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  67375. },
  67376. enumerable: true,
  67377. configurable: true
  67378. });
  67379. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  67380. get: function () {
  67381. return this._buttonX;
  67382. },
  67383. set: function (value) {
  67384. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  67385. },
  67386. enumerable: true,
  67387. configurable: true
  67388. });
  67389. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  67390. get: function () {
  67391. return this._buttonY;
  67392. },
  67393. set: function (value) {
  67394. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  67395. },
  67396. enumerable: true,
  67397. configurable: true
  67398. });
  67399. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  67400. get: function () {
  67401. return this._buttonStart;
  67402. },
  67403. set: function (value) {
  67404. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  67405. },
  67406. enumerable: true,
  67407. configurable: true
  67408. });
  67409. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  67410. get: function () {
  67411. return this._buttonBack;
  67412. },
  67413. set: function (value) {
  67414. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  67415. },
  67416. enumerable: true,
  67417. configurable: true
  67418. });
  67419. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  67420. get: function () {
  67421. return this._buttonLB;
  67422. },
  67423. set: function (value) {
  67424. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  67425. },
  67426. enumerable: true,
  67427. configurable: true
  67428. });
  67429. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  67430. get: function () {
  67431. return this._buttonRB;
  67432. },
  67433. set: function (value) {
  67434. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  67435. },
  67436. enumerable: true,
  67437. configurable: true
  67438. });
  67439. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  67440. get: function () {
  67441. return this._buttonLeftStick;
  67442. },
  67443. set: function (value) {
  67444. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  67445. },
  67446. enumerable: true,
  67447. configurable: true
  67448. });
  67449. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  67450. get: function () {
  67451. return this._buttonRightStick;
  67452. },
  67453. set: function (value) {
  67454. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  67455. },
  67456. enumerable: true,
  67457. configurable: true
  67458. });
  67459. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  67460. get: function () {
  67461. return this._dPadUp;
  67462. },
  67463. set: function (value) {
  67464. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  67465. },
  67466. enumerable: true,
  67467. configurable: true
  67468. });
  67469. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  67470. get: function () {
  67471. return this._dPadDown;
  67472. },
  67473. set: function (value) {
  67474. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  67475. },
  67476. enumerable: true,
  67477. configurable: true
  67478. });
  67479. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  67480. get: function () {
  67481. return this._dPadLeft;
  67482. },
  67483. set: function (value) {
  67484. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  67485. },
  67486. enumerable: true,
  67487. configurable: true
  67488. });
  67489. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  67490. get: function () {
  67491. return this._dPadRight;
  67492. },
  67493. set: function (value) {
  67494. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  67495. },
  67496. enumerable: true,
  67497. configurable: true
  67498. });
  67499. Xbox360Pad.prototype.update = function () {
  67500. _super.prototype.update.call(this);
  67501. if (this._isXboxOnePad) {
  67502. this.buttonA = this.browserGamepad.buttons[0].value;
  67503. this.buttonB = this.browserGamepad.buttons[1].value;
  67504. this.buttonX = this.browserGamepad.buttons[2].value;
  67505. this.buttonY = this.browserGamepad.buttons[3].value;
  67506. this.buttonLB = this.browserGamepad.buttons[4].value;
  67507. this.buttonRB = this.browserGamepad.buttons[5].value;
  67508. this.leftTrigger = this.browserGamepad.axes[2];
  67509. this.rightTrigger = this.browserGamepad.axes[5];
  67510. this.buttonBack = this.browserGamepad.buttons[9].value;
  67511. this.buttonStart = this.browserGamepad.buttons[8].value;
  67512. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  67513. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  67514. this.dPadUp = this.browserGamepad.buttons[11].value;
  67515. this.dPadDown = this.browserGamepad.buttons[12].value;
  67516. this.dPadLeft = this.browserGamepad.buttons[13].value;
  67517. this.dPadRight = this.browserGamepad.buttons[14].value;
  67518. }
  67519. else {
  67520. this.buttonA = this.browserGamepad.buttons[0].value;
  67521. this.buttonB = this.browserGamepad.buttons[1].value;
  67522. this.buttonX = this.browserGamepad.buttons[2].value;
  67523. this.buttonY = this.browserGamepad.buttons[3].value;
  67524. this.buttonLB = this.browserGamepad.buttons[4].value;
  67525. this.buttonRB = this.browserGamepad.buttons[5].value;
  67526. this.leftTrigger = this.browserGamepad.buttons[6].value;
  67527. this.rightTrigger = this.browserGamepad.buttons[7].value;
  67528. this.buttonBack = this.browserGamepad.buttons[8].value;
  67529. this.buttonStart = this.browserGamepad.buttons[9].value;
  67530. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  67531. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  67532. this.dPadUp = this.browserGamepad.buttons[12].value;
  67533. this.dPadDown = this.browserGamepad.buttons[13].value;
  67534. this.dPadLeft = this.browserGamepad.buttons[14].value;
  67535. this.dPadRight = this.browserGamepad.buttons[15].value;
  67536. }
  67537. };
  67538. Xbox360Pad.prototype.dispose = function () {
  67539. _super.prototype.dispose.call(this);
  67540. this.onButtonDownObservable.clear();
  67541. this.onButtonUpObservable.clear();
  67542. this.onPadDownObservable.clear();
  67543. this.onPadUpObservable.clear();
  67544. };
  67545. return Xbox360Pad;
  67546. }(BABYLON.Gamepad));
  67547. BABYLON.Xbox360Pad = Xbox360Pad;
  67548. })(BABYLON || (BABYLON = {}));
  67549. //# sourceMappingURL=babylon.xboxGamepad.js.map
  67550. "use strict";
  67551. var BABYLON;
  67552. (function (BABYLON) {
  67553. var PoseEnabledControllerType;
  67554. (function (PoseEnabledControllerType) {
  67555. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  67556. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  67557. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  67558. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  67559. /**
  67560. * Google Daydream
  67561. */
  67562. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  67563. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  67564. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  67565. var PoseEnabledControllerHelper = /** @class */ (function () {
  67566. function PoseEnabledControllerHelper() {
  67567. }
  67568. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  67569. // Oculus Touch
  67570. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  67571. return new BABYLON.OculusTouchController(vrGamepad);
  67572. }
  67573. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  67574. return new BABYLON.WindowsMotionController(vrGamepad);
  67575. }
  67576. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  67577. return new BABYLON.ViveController(vrGamepad);
  67578. }
  67579. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  67580. return new BABYLON.GearVRController(vrGamepad);
  67581. }
  67582. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  67583. return new BABYLON.DaydreamController(vrGamepad);
  67584. }
  67585. else {
  67586. return new BABYLON.GenericController(vrGamepad);
  67587. }
  67588. };
  67589. return PoseEnabledControllerHelper;
  67590. }());
  67591. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  67592. var PoseEnabledController = /** @class */ (function (_super) {
  67593. __extends(PoseEnabledController, _super);
  67594. function PoseEnabledController(browserGamepad) {
  67595. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  67596. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  67597. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  67598. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  67599. // Represents device position and rotation in babylon space
  67600. _this.devicePosition = BABYLON.Vector3.Zero();
  67601. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  67602. _this.deviceScaleFactor = 1;
  67603. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  67604. _this._deviceToWorld = BABYLON.Matrix.Identity();
  67605. /**
  67606. * Node to be used when casting a ray from the controller
  67607. */
  67608. _this._pointingPoseNode = null;
  67609. _this._workingMatrix = BABYLON.Matrix.Identity();
  67610. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  67611. _this.controllerType = PoseEnabledControllerType.GENERIC;
  67612. _this.position = BABYLON.Vector3.Zero();
  67613. _this.rotationQuaternion = new BABYLON.Quaternion();
  67614. _this._calculatedPosition = BABYLON.Vector3.Zero();
  67615. _this._calculatedRotation = new BABYLON.Quaternion();
  67616. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  67617. return _this;
  67618. }
  67619. PoseEnabledController.prototype.update = function () {
  67620. _super.prototype.update.call(this);
  67621. var pose = this.browserGamepad.pose;
  67622. this.updateFromDevice(pose);
  67623. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  67624. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  67625. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  67626. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  67627. if (this._mesh) {
  67628. this._mesh.position.copyFrom(this.devicePosition);
  67629. if (this._mesh.rotationQuaternion) {
  67630. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  67631. }
  67632. }
  67633. };
  67634. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  67635. if (poseData) {
  67636. this.rawPose = poseData;
  67637. if (poseData.position) {
  67638. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  67639. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  67640. this._deviceRoomPosition.z *= -1;
  67641. }
  67642. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  67643. this._calculatedPosition.addInPlace(this.position);
  67644. }
  67645. var pose = this.rawPose;
  67646. if (poseData.orientation && pose.orientation) {
  67647. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  67648. if (this._mesh) {
  67649. if (this._mesh.getScene().useRightHandedSystem) {
  67650. this._deviceRoomRotationQuaternion.z *= -1;
  67651. this._deviceRoomRotationQuaternion.w *= -1;
  67652. }
  67653. else {
  67654. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  67655. }
  67656. }
  67657. // if the camera is set, rotate to the camera's rotation
  67658. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  67659. }
  67660. }
  67661. };
  67662. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  67663. if (this._mesh) {
  67664. this._mesh.parent = null;
  67665. }
  67666. this._mesh = mesh;
  67667. if (this._poseControlledCamera) {
  67668. this._mesh.parent = this._poseControlledCamera;
  67669. }
  67670. if (!this._mesh.rotationQuaternion) {
  67671. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  67672. }
  67673. };
  67674. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  67675. this._poseControlledCamera = camera;
  67676. if (this._mesh) {
  67677. this._mesh.parent = this._poseControlledCamera;
  67678. }
  67679. };
  67680. PoseEnabledController.prototype.dispose = function () {
  67681. if (this._mesh) {
  67682. this._mesh.dispose();
  67683. }
  67684. this._mesh = null;
  67685. _super.prototype.dispose.call(this);
  67686. };
  67687. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  67688. get: function () {
  67689. return this._mesh;
  67690. },
  67691. enumerable: true,
  67692. configurable: true
  67693. });
  67694. PoseEnabledController.prototype.getForwardRay = function (length) {
  67695. if (length === void 0) { length = 100; }
  67696. if (!this.mesh) {
  67697. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  67698. }
  67699. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  67700. var origin = m.getTranslation();
  67701. var forward = new BABYLON.Vector3(0, 0, -1);
  67702. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67703. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67704. return new BABYLON.Ray(origin, direction, length);
  67705. };
  67706. /**
  67707. * Name of the child mesh that can be used to cast a ray from the controller
  67708. */
  67709. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  67710. return PoseEnabledController;
  67711. }(BABYLON.Gamepad));
  67712. BABYLON.PoseEnabledController = PoseEnabledController;
  67713. })(BABYLON || (BABYLON = {}));
  67714. //# sourceMappingURL=babylon.poseEnabledController.js.map
  67715. "use strict";
  67716. var BABYLON;
  67717. (function (BABYLON) {
  67718. var WebVRController = /** @class */ (function (_super) {
  67719. __extends(WebVRController, _super);
  67720. function WebVRController(vrGamepad) {
  67721. var _this = _super.call(this, vrGamepad) || this;
  67722. // Observables
  67723. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  67724. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  67725. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  67726. _this.onPadStateChangedObservable = new BABYLON.Observable();
  67727. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  67728. _this.pad = { x: 0, y: 0 };
  67729. // avoid GC, store state in a tmp object
  67730. _this._changes = {
  67731. pressChanged: false,
  67732. touchChanged: false,
  67733. valueChanged: false,
  67734. changed: false
  67735. };
  67736. _this._buttons = new Array(vrGamepad.buttons.length);
  67737. _this.hand = vrGamepad.hand;
  67738. return _this;
  67739. }
  67740. WebVRController.prototype.onButtonStateChange = function (callback) {
  67741. this._onButtonStateChange = callback;
  67742. };
  67743. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  67744. get: function () {
  67745. return this._defaultModel;
  67746. },
  67747. enumerable: true,
  67748. configurable: true
  67749. });
  67750. WebVRController.prototype.update = function () {
  67751. _super.prototype.update.call(this);
  67752. for (var index = 0; index < this._buttons.length; index++) {
  67753. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  67754. }
  67755. ;
  67756. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  67757. this.pad.x = this.leftStick.x;
  67758. this.pad.y = this.leftStick.y;
  67759. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  67760. }
  67761. };
  67762. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  67763. if (!newState) {
  67764. newState = {
  67765. pressed: false,
  67766. touched: false,
  67767. value: 0
  67768. };
  67769. }
  67770. if (!currentState) {
  67771. this._buttons[buttonIndex] = {
  67772. pressed: newState.pressed,
  67773. touched: newState.touched,
  67774. value: newState.value
  67775. };
  67776. return;
  67777. }
  67778. this._checkChanges(newState, currentState);
  67779. if (this._changes.changed) {
  67780. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  67781. this._handleButtonChange(buttonIndex, newState, this._changes);
  67782. }
  67783. this._buttons[buttonIndex].pressed = newState.pressed;
  67784. this._buttons[buttonIndex].touched = newState.touched;
  67785. // oculus triggers are never 0, thou not touched.
  67786. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  67787. };
  67788. WebVRController.prototype._checkChanges = function (newState, currentState) {
  67789. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  67790. this._changes.touchChanged = newState.touched !== currentState.touched;
  67791. this._changes.valueChanged = newState.value !== currentState.value;
  67792. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  67793. return this._changes;
  67794. };
  67795. WebVRController.prototype.dispose = function () {
  67796. _super.prototype.dispose.call(this);
  67797. this.onTriggerStateChangedObservable.clear();
  67798. this.onMainButtonStateChangedObservable.clear();
  67799. this.onSecondaryButtonStateChangedObservable.clear();
  67800. this.onPadStateChangedObservable.clear();
  67801. this.onPadValuesChangedObservable.clear();
  67802. };
  67803. return WebVRController;
  67804. }(BABYLON.PoseEnabledController));
  67805. BABYLON.WebVRController = WebVRController;
  67806. })(BABYLON || (BABYLON = {}));
  67807. //# sourceMappingURL=babylon.webVRController.js.map
  67808. "use strict";
  67809. var BABYLON;
  67810. (function (BABYLON) {
  67811. var OculusTouchController = /** @class */ (function (_super) {
  67812. __extends(OculusTouchController, _super);
  67813. function OculusTouchController(vrGamepad) {
  67814. var _this = _super.call(this, vrGamepad) || this;
  67815. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  67816. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  67817. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  67818. return _this;
  67819. }
  67820. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67821. var _this = this;
  67822. var meshName;
  67823. // Hand
  67824. if (this.hand === 'left') {
  67825. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  67826. }
  67827. else {
  67828. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  67829. }
  67830. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  67831. /*
  67832. Parent Mesh name: oculus_touch_left
  67833. - body
  67834. - trigger
  67835. - thumbstick
  67836. - grip
  67837. - button_y
  67838. - button_x
  67839. - button_enter
  67840. */
  67841. _this._defaultModel = newMeshes[1];
  67842. _this.attachToMesh(_this._defaultModel);
  67843. if (meshLoaded) {
  67844. meshLoaded(_this._defaultModel);
  67845. }
  67846. });
  67847. };
  67848. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  67849. // helper getters for left and right hand.
  67850. get: function () {
  67851. if (this.hand === 'right') {
  67852. return this.onMainButtonStateChangedObservable;
  67853. }
  67854. else {
  67855. throw new Error('No A button on left hand');
  67856. }
  67857. },
  67858. enumerable: true,
  67859. configurable: true
  67860. });
  67861. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  67862. get: function () {
  67863. if (this.hand === 'right') {
  67864. return this.onSecondaryButtonStateChangedObservable;
  67865. }
  67866. else {
  67867. throw new Error('No B button on left hand');
  67868. }
  67869. },
  67870. enumerable: true,
  67871. configurable: true
  67872. });
  67873. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  67874. get: function () {
  67875. if (this.hand === 'left') {
  67876. return this.onMainButtonStateChangedObservable;
  67877. }
  67878. else {
  67879. throw new Error('No X button on right hand');
  67880. }
  67881. },
  67882. enumerable: true,
  67883. configurable: true
  67884. });
  67885. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  67886. get: function () {
  67887. if (this.hand === 'left') {
  67888. return this.onSecondaryButtonStateChangedObservable;
  67889. }
  67890. else {
  67891. throw new Error('No Y button on right hand');
  67892. }
  67893. },
  67894. enumerable: true,
  67895. configurable: true
  67896. });
  67897. /*
  67898. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  67899. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  67900. 2) secondary trigger (same)
  67901. 3) A (right) X (left), touch, pressed = value
  67902. 4) B / Y
  67903. 5) thumb rest
  67904. */
  67905. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67906. var notifyObject = state; //{ state: state, changes: changes };
  67907. var triggerDirection = this.hand === 'right' ? -1 : 1;
  67908. switch (buttonIdx) {
  67909. case 0:
  67910. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67911. return;
  67912. case 1:// index trigger
  67913. if (this._defaultModel) {
  67914. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  67915. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  67916. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  67917. }
  67918. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67919. return;
  67920. case 2:// secondary trigger
  67921. if (this._defaultModel) {
  67922. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  67923. }
  67924. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  67925. return;
  67926. case 3:
  67927. if (this._defaultModel) {
  67928. if (notifyObject.pressed) {
  67929. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  67930. }
  67931. else {
  67932. (this._defaultModel.getChildren()[1]).position.y = 0;
  67933. }
  67934. }
  67935. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67936. return;
  67937. case 4:
  67938. if (this._defaultModel) {
  67939. if (notifyObject.pressed) {
  67940. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67941. }
  67942. else {
  67943. (this._defaultModel.getChildren()[2]).position.y = 0;
  67944. }
  67945. }
  67946. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67947. return;
  67948. case 5:
  67949. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  67950. return;
  67951. }
  67952. };
  67953. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  67954. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  67955. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  67956. return OculusTouchController;
  67957. }(BABYLON.WebVRController));
  67958. BABYLON.OculusTouchController = OculusTouchController;
  67959. })(BABYLON || (BABYLON = {}));
  67960. //# sourceMappingURL=babylon.oculusTouchController.js.map
  67961. "use strict";
  67962. var BABYLON;
  67963. (function (BABYLON) {
  67964. var ViveController = /** @class */ (function (_super) {
  67965. __extends(ViveController, _super);
  67966. function ViveController(vrGamepad) {
  67967. var _this = _super.call(this, vrGamepad) || this;
  67968. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  67969. _this._invertLeftStickY = true;
  67970. return _this;
  67971. }
  67972. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67973. var _this = this;
  67974. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  67975. /*
  67976. Parent Mesh name: ViveWand
  67977. - body
  67978. - r_gripper
  67979. - l_gripper
  67980. - menu_button
  67981. - system_button
  67982. - trackpad
  67983. - trigger
  67984. - LED
  67985. */
  67986. _this._defaultModel = newMeshes[1];
  67987. _this.attachToMesh(_this._defaultModel);
  67988. if (meshLoaded) {
  67989. meshLoaded(_this._defaultModel);
  67990. }
  67991. });
  67992. };
  67993. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  67994. get: function () {
  67995. return this.onMainButtonStateChangedObservable;
  67996. },
  67997. enumerable: true,
  67998. configurable: true
  67999. });
  68000. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  68001. get: function () {
  68002. return this.onMainButtonStateChangedObservable;
  68003. },
  68004. enumerable: true,
  68005. configurable: true
  68006. });
  68007. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  68008. get: function () {
  68009. return this.onSecondaryButtonStateChangedObservable;
  68010. },
  68011. enumerable: true,
  68012. configurable: true
  68013. });
  68014. /**
  68015. * Vive mapping:
  68016. * 0: touchpad
  68017. * 1: trigger
  68018. * 2: left AND right buttons
  68019. * 3: menu button
  68020. */
  68021. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  68022. var notifyObject = state; //{ state: state, changes: changes };
  68023. switch (buttonIdx) {
  68024. case 0:
  68025. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  68026. return;
  68027. case 1:// index trigger
  68028. if (this._defaultModel) {
  68029. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  68030. }
  68031. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  68032. return;
  68033. case 2:// left AND right button
  68034. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  68035. return;
  68036. case 3:
  68037. if (this._defaultModel) {
  68038. if (notifyObject.pressed) {
  68039. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  68040. }
  68041. else {
  68042. (this._defaultModel.getChildren()[2]).position.y = 0;
  68043. }
  68044. }
  68045. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  68046. return;
  68047. }
  68048. };
  68049. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  68050. ViveController.MODEL_FILENAME = 'wand.babylon';
  68051. return ViveController;
  68052. }(BABYLON.WebVRController));
  68053. BABYLON.ViveController = ViveController;
  68054. })(BABYLON || (BABYLON = {}));
  68055. //# sourceMappingURL=babylon.viveController.js.map
  68056. "use strict";
  68057. var BABYLON;
  68058. (function (BABYLON) {
  68059. var GenericController = /** @class */ (function (_super) {
  68060. __extends(GenericController, _super);
  68061. function GenericController(vrGamepad) {
  68062. return _super.call(this, vrGamepad) || this;
  68063. }
  68064. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  68065. var _this = this;
  68066. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  68067. _this._defaultModel = newMeshes[1];
  68068. _this.attachToMesh(_this._defaultModel);
  68069. if (meshLoaded) {
  68070. meshLoaded(_this._defaultModel);
  68071. }
  68072. });
  68073. };
  68074. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  68075. console.log("Button id: " + buttonIdx + "state: ");
  68076. console.dir(state);
  68077. };
  68078. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  68079. GenericController.MODEL_FILENAME = 'generic.babylon';
  68080. return GenericController;
  68081. }(BABYLON.WebVRController));
  68082. BABYLON.GenericController = GenericController;
  68083. })(BABYLON || (BABYLON = {}));
  68084. //# sourceMappingURL=babylon.genericController.js.map
  68085. "use strict";
  68086. var BABYLON;
  68087. (function (BABYLON) {
  68088. var LoadedMeshInfo = /** @class */ (function () {
  68089. function LoadedMeshInfo() {
  68090. this.buttonMeshes = {};
  68091. this.axisMeshes = {};
  68092. }
  68093. return LoadedMeshInfo;
  68094. }());
  68095. var WindowsMotionController = /** @class */ (function (_super) {
  68096. __extends(WindowsMotionController, _super);
  68097. function WindowsMotionController(vrGamepad) {
  68098. var _this = _super.call(this, vrGamepad) || this;
  68099. _this._mapping = {
  68100. // Semantic button names
  68101. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  68102. // A mapping of the button name to glTF model node name
  68103. // that should be transformed by button value.
  68104. buttonMeshNames: {
  68105. 'trigger': 'SELECT',
  68106. 'menu': 'MENU',
  68107. 'grip': 'GRASP',
  68108. 'thumbstick': 'THUMBSTICK_PRESS',
  68109. 'trackpad': 'TOUCHPAD_PRESS'
  68110. },
  68111. // This mapping is used to translate from the Motion Controller to Babylon semantics
  68112. buttonObservableNames: {
  68113. 'trigger': 'onTriggerStateChangedObservable',
  68114. 'menu': 'onSecondaryButtonStateChangedObservable',
  68115. 'grip': 'onMainButtonStateChangedObservable',
  68116. 'thumbstick': 'onPadStateChangedObservable',
  68117. 'trackpad': 'onTrackpadChangedObservable'
  68118. },
  68119. // A mapping of the axis name to glTF model node name
  68120. // that should be transformed by axis value.
  68121. // This array mirrors the browserGamepad.axes array, such that
  68122. // the mesh corresponding to axis 0 is in this array index 0.
  68123. axisMeshNames: [
  68124. 'THUMBSTICK_X',
  68125. 'THUMBSTICK_Y',
  68126. 'TOUCHPAD_TOUCH_X',
  68127. 'TOUCHPAD_TOUCH_Y'
  68128. ],
  68129. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  68130. };
  68131. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  68132. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  68133. _this.trackpad = { x: 0, y: 0 };
  68134. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  68135. _this._loadedMeshInfo = null;
  68136. return _this;
  68137. }
  68138. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  68139. get: function () {
  68140. return this.onTriggerStateChangedObservable;
  68141. },
  68142. enumerable: true,
  68143. configurable: true
  68144. });
  68145. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  68146. get: function () {
  68147. return this.onSecondaryButtonStateChangedObservable;
  68148. },
  68149. enumerable: true,
  68150. configurable: true
  68151. });
  68152. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  68153. get: function () {
  68154. return this.onMainButtonStateChangedObservable;
  68155. },
  68156. enumerable: true,
  68157. configurable: true
  68158. });
  68159. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  68160. get: function () {
  68161. return this.onPadStateChangedObservable;
  68162. },
  68163. enumerable: true,
  68164. configurable: true
  68165. });
  68166. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  68167. get: function () {
  68168. return this.onTrackpadChangedObservable;
  68169. },
  68170. enumerable: true,
  68171. configurable: true
  68172. });
  68173. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  68174. get: function () {
  68175. return this.onTrackpadValuesChangedObservable;
  68176. },
  68177. enumerable: true,
  68178. configurable: true
  68179. });
  68180. /**
  68181. * Called once per frame by the engine.
  68182. */
  68183. WindowsMotionController.prototype.update = function () {
  68184. _super.prototype.update.call(this);
  68185. if (this.browserGamepad.axes) {
  68186. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  68187. this.trackpad.x = this.browserGamepad["axes"][2];
  68188. this.trackpad.y = this.browserGamepad["axes"][3];
  68189. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  68190. }
  68191. // Only need to animate axes if there is a loaded mesh
  68192. if (this._loadedMeshInfo) {
  68193. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  68194. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  68195. }
  68196. }
  68197. }
  68198. };
  68199. /**
  68200. * Called once for each button that changed state since the last frame
  68201. * @param buttonIdx Which button index changed
  68202. * @param state New state of the button
  68203. * @param changes Which properties on the state changed since last frame
  68204. */
  68205. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  68206. var buttonName = this._mapping.buttons[buttonIdx];
  68207. if (!buttonName) {
  68208. return;
  68209. }
  68210. // Only emit events for buttons that we know how to map from index to name
  68211. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  68212. if (observable) {
  68213. observable.notifyObservers(state);
  68214. }
  68215. this.lerpButtonTransform(buttonName, state.value);
  68216. };
  68217. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  68218. // If there is no loaded mesh, there is nothing to transform.
  68219. if (!this._loadedMeshInfo) {
  68220. return;
  68221. }
  68222. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  68223. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  68224. return;
  68225. }
  68226. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  68227. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  68228. };
  68229. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  68230. if (!this._loadedMeshInfo) {
  68231. return;
  68232. }
  68233. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  68234. if (!meshInfo) {
  68235. return;
  68236. }
  68237. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  68238. return;
  68239. }
  68240. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  68241. var lerpValue = axisValue * 0.5 + 0.5;
  68242. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  68243. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  68244. };
  68245. /**
  68246. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  68247. * @param scene scene in which to add meshes
  68248. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  68249. */
  68250. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  68251. var _this = this;
  68252. if (forceDefault === void 0) { forceDefault = false; }
  68253. var path;
  68254. var filename;
  68255. // Checking if GLB loader is present
  68256. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  68257. // Determine the device specific folder based on the ID suffix
  68258. var device = 'default';
  68259. if (this.id && !forceDefault) {
  68260. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  68261. device = ((match && match[0]) || device);
  68262. }
  68263. // Hand
  68264. if (this.hand === 'left') {
  68265. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  68266. }
  68267. else {
  68268. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  68269. }
  68270. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  68271. }
  68272. else {
  68273. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  68274. path = BABYLON.GenericController.MODEL_BASE_URL;
  68275. filename = BABYLON.GenericController.MODEL_FILENAME;
  68276. }
  68277. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  68278. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  68279. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  68280. if (!_this._loadedMeshInfo) {
  68281. return;
  68282. }
  68283. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  68284. _this.attachToMesh(_this._defaultModel);
  68285. if (meshLoaded) {
  68286. meshLoaded(_this._defaultModel);
  68287. }
  68288. }, null, function (scene, message) {
  68289. BABYLON.Tools.Log(message);
  68290. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  68291. if (!forceDefault) {
  68292. _this.initControllerMesh(scene, meshLoaded, true);
  68293. }
  68294. });
  68295. };
  68296. /**
  68297. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  68298. * can be transformed by button presses and axes values, based on this._mapping.
  68299. *
  68300. * @param scene scene in which the meshes exist
  68301. * @param meshes list of meshes that make up the controller model to process
  68302. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  68303. */
  68304. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  68305. var loadedMeshInfo = null;
  68306. // Create a new mesh to contain the glTF hierarchy
  68307. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  68308. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  68309. var childMesh = null;
  68310. for (var i = 0; i < meshes.length; i++) {
  68311. var mesh = meshes[i];
  68312. if (!mesh.parent) {
  68313. // Exclude controller meshes from picking results
  68314. mesh.isPickable = false;
  68315. // Handle root node, attach to the new parentMesh
  68316. childMesh = mesh;
  68317. break;
  68318. }
  68319. }
  68320. if (childMesh) {
  68321. childMesh.setParent(parentMesh);
  68322. // Create our mesh info. Note that this method will always return non-null.
  68323. loadedMeshInfo = this.createMeshInfo(parentMesh);
  68324. }
  68325. else {
  68326. BABYLON.Tools.Warn('Could not find root node in model file.');
  68327. }
  68328. return loadedMeshInfo;
  68329. };
  68330. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  68331. var loadedMeshInfo = new LoadedMeshInfo();
  68332. var i;
  68333. loadedMeshInfo.rootNode = rootNode;
  68334. // Reset the caches
  68335. loadedMeshInfo.buttonMeshes = {};
  68336. loadedMeshInfo.axisMeshes = {};
  68337. // Button Meshes
  68338. for (i = 0; i < this._mapping.buttons.length; i++) {
  68339. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  68340. if (!buttonMeshName) {
  68341. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  68342. continue;
  68343. }
  68344. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  68345. if (!buttonMesh) {
  68346. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  68347. continue;
  68348. }
  68349. var buttonMeshInfo = {
  68350. index: i,
  68351. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  68352. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  68353. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  68354. };
  68355. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  68356. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  68357. }
  68358. else {
  68359. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  68360. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  68361. '(VALUE: ' + !!buttonMeshInfo.value +
  68362. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  68363. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  68364. ')');
  68365. }
  68366. }
  68367. // Axis Meshes
  68368. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  68369. var axisMeshName = this._mapping.axisMeshNames[i];
  68370. if (!axisMeshName) {
  68371. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  68372. continue;
  68373. }
  68374. var axisMesh = getChildByName(rootNode, axisMeshName);
  68375. if (!axisMesh) {
  68376. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  68377. continue;
  68378. }
  68379. var axisMeshInfo = {
  68380. index: i,
  68381. value: getImmediateChildByName(axisMesh, 'VALUE'),
  68382. min: getImmediateChildByName(axisMesh, 'MIN'),
  68383. max: getImmediateChildByName(axisMesh, 'MAX')
  68384. };
  68385. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  68386. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  68387. }
  68388. else {
  68389. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  68390. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  68391. '(VALUE: ' + !!axisMeshInfo.value +
  68392. ', MIN: ' + !!axisMeshInfo.min +
  68393. ', MAX:' + !!axisMeshInfo.max +
  68394. ')');
  68395. }
  68396. }
  68397. // Pointing Ray
  68398. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  68399. if (!loadedMeshInfo.pointingPoseNode) {
  68400. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  68401. }
  68402. return loadedMeshInfo;
  68403. // Look through all children recursively. This will return null if no mesh exists with the given name.
  68404. function getChildByName(node, name) {
  68405. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  68406. }
  68407. // Look through only immediate children. This will return null if no mesh exists with the given name.
  68408. function getImmediateChildByName(node, name) {
  68409. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  68410. }
  68411. };
  68412. WindowsMotionController.prototype.getForwardRay = function (length) {
  68413. if (length === void 0) { length = 100; }
  68414. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  68415. return _super.prototype.getForwardRay.call(this, length);
  68416. }
  68417. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  68418. var origin = m.getTranslation();
  68419. var forward = new BABYLON.Vector3(0, 0, -1);
  68420. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  68421. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  68422. return new BABYLON.Ray(origin, direction, length);
  68423. };
  68424. WindowsMotionController.prototype.dispose = function () {
  68425. _super.prototype.dispose.call(this);
  68426. this.onTrackpadChangedObservable.clear();
  68427. };
  68428. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  68429. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  68430. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  68431. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  68432. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  68433. return WindowsMotionController;
  68434. }(BABYLON.WebVRController));
  68435. BABYLON.WindowsMotionController = WindowsMotionController;
  68436. })(BABYLON || (BABYLON = {}));
  68437. //# sourceMappingURL=babylon.windowsMotionController.js.map
  68438. "use strict";
  68439. var BABYLON;
  68440. (function (BABYLON) {
  68441. var GearVRController = /** @class */ (function (_super) {
  68442. __extends(GearVRController, _super);
  68443. function GearVRController(vrGamepad) {
  68444. var _this = _super.call(this, vrGamepad) || this;
  68445. _this._buttonIndexToObservableNameMap = [
  68446. 'onTrackpadChangedObservable',
  68447. 'onTriggerStateChangedObservable' // Trigger
  68448. ];
  68449. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  68450. return _this;
  68451. }
  68452. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  68453. var _this = this;
  68454. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  68455. _this._defaultModel = newMeshes[1];
  68456. _this.attachToMesh(_this._defaultModel);
  68457. if (meshLoaded) {
  68458. meshLoaded(_this._defaultModel);
  68459. }
  68460. });
  68461. };
  68462. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  68463. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  68464. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  68465. // Only emit events for buttons that we know how to map from index to observable
  68466. var observable = this[observableName];
  68467. if (observable) {
  68468. observable.notifyObservers(state);
  68469. }
  68470. }
  68471. };
  68472. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  68473. GearVRController.MODEL_FILENAME = 'generic.babylon';
  68474. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  68475. return GearVRController;
  68476. }(BABYLON.WebVRController));
  68477. BABYLON.GearVRController = GearVRController;
  68478. })(BABYLON || (BABYLON = {}));
  68479. //# sourceMappingURL=babylon.gearVRController.js.map
  68480. "use strict";
  68481. var BABYLON;
  68482. (function (BABYLON) {
  68483. /**
  68484. * Google Daydream controller
  68485. */
  68486. var DaydreamController = /** @class */ (function (_super) {
  68487. __extends(DaydreamController, _super);
  68488. function DaydreamController(vrGamepad) {
  68489. var _this = _super.call(this, vrGamepad) || this;
  68490. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  68491. return _this;
  68492. }
  68493. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  68494. var _this = this;
  68495. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  68496. _this._defaultModel = newMeshes[1];
  68497. _this.attachToMesh(_this._defaultModel);
  68498. if (meshLoaded) {
  68499. meshLoaded(_this._defaultModel);
  68500. }
  68501. });
  68502. };
  68503. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  68504. // Daydream controller only has 1 GamepadButton (on the trackpad).
  68505. if (buttonIdx === 0) {
  68506. var observable = this.onTriggerStateChangedObservable;
  68507. if (observable) {
  68508. observable.notifyObservers(state);
  68509. }
  68510. }
  68511. else {
  68512. // If the app or home buttons are ever made available
  68513. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  68514. }
  68515. };
  68516. /**
  68517. * Base Url for the controller model.
  68518. */
  68519. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  68520. /**
  68521. * File name for the controller model.
  68522. */
  68523. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  68524. /**
  68525. * Gamepad Id prefix used to identify Daydream Controller.
  68526. */
  68527. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  68528. return DaydreamController;
  68529. }(BABYLON.WebVRController));
  68530. BABYLON.DaydreamController = DaydreamController;
  68531. })(BABYLON || (BABYLON = {}));
  68532. //# sourceMappingURL=babylon.daydreamController.js.map
  68533. "use strict";
  68534. var BABYLON;
  68535. (function (BABYLON) {
  68536. var FollowCamera = /** @class */ (function (_super) {
  68537. __extends(FollowCamera, _super);
  68538. function FollowCamera(name, position, scene, lockedTarget) {
  68539. if (lockedTarget === void 0) { lockedTarget = null; }
  68540. var _this = _super.call(this, name, position, scene) || this;
  68541. _this.radius = 12;
  68542. _this.rotationOffset = 0;
  68543. _this.heightOffset = 4;
  68544. _this.cameraAcceleration = 0.05;
  68545. _this.maxCameraSpeed = 20;
  68546. _this.lockedTarget = lockedTarget;
  68547. return _this;
  68548. }
  68549. FollowCamera.prototype.getRadians = function (degrees) {
  68550. return degrees * Math.PI / 180;
  68551. };
  68552. FollowCamera.prototype.follow = function (cameraTarget) {
  68553. if (!cameraTarget)
  68554. return;
  68555. var yRotation;
  68556. if (cameraTarget.rotationQuaternion) {
  68557. var rotMatrix = new BABYLON.Matrix();
  68558. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  68559. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  68560. }
  68561. else {
  68562. yRotation = cameraTarget.rotation.y;
  68563. }
  68564. var radians = this.getRadians(this.rotationOffset) + yRotation;
  68565. var targetPosition = cameraTarget.getAbsolutePosition();
  68566. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  68567. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  68568. var dx = targetX - this.position.x;
  68569. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  68570. var dz = (targetZ) - this.position.z;
  68571. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  68572. var vy = dy * this.cameraAcceleration;
  68573. var vz = dz * this.cameraAcceleration * 2;
  68574. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  68575. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  68576. }
  68577. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  68578. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  68579. }
  68580. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  68581. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  68582. }
  68583. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  68584. this.setTarget(targetPosition);
  68585. };
  68586. FollowCamera.prototype._checkInputs = function () {
  68587. _super.prototype._checkInputs.call(this);
  68588. if (this.lockedTarget) {
  68589. this.follow(this.lockedTarget);
  68590. }
  68591. };
  68592. FollowCamera.prototype.getClassName = function () {
  68593. return "FollowCamera";
  68594. };
  68595. __decorate([
  68596. BABYLON.serialize()
  68597. ], FollowCamera.prototype, "radius", void 0);
  68598. __decorate([
  68599. BABYLON.serialize()
  68600. ], FollowCamera.prototype, "rotationOffset", void 0);
  68601. __decorate([
  68602. BABYLON.serialize()
  68603. ], FollowCamera.prototype, "heightOffset", void 0);
  68604. __decorate([
  68605. BABYLON.serialize()
  68606. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  68607. __decorate([
  68608. BABYLON.serialize()
  68609. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  68610. __decorate([
  68611. BABYLON.serializeAsMeshReference("lockedTargetId")
  68612. ], FollowCamera.prototype, "lockedTarget", void 0);
  68613. return FollowCamera;
  68614. }(BABYLON.TargetCamera));
  68615. BABYLON.FollowCamera = FollowCamera;
  68616. var ArcFollowCamera = /** @class */ (function (_super) {
  68617. __extends(ArcFollowCamera, _super);
  68618. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  68619. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  68620. _this.alpha = alpha;
  68621. _this.beta = beta;
  68622. _this.radius = radius;
  68623. _this.target = target;
  68624. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  68625. _this.follow();
  68626. return _this;
  68627. }
  68628. ArcFollowCamera.prototype.follow = function () {
  68629. if (!this.target) {
  68630. return;
  68631. }
  68632. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  68633. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  68634. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  68635. var targetPosition = this.target.getAbsolutePosition();
  68636. this.position = targetPosition.add(this._cartesianCoordinates);
  68637. this.setTarget(targetPosition);
  68638. };
  68639. ArcFollowCamera.prototype._checkInputs = function () {
  68640. _super.prototype._checkInputs.call(this);
  68641. this.follow();
  68642. };
  68643. ArcFollowCamera.prototype.getClassName = function () {
  68644. return "ArcFollowCamera";
  68645. };
  68646. return ArcFollowCamera;
  68647. }(BABYLON.TargetCamera));
  68648. BABYLON.ArcFollowCamera = ArcFollowCamera;
  68649. })(BABYLON || (BABYLON = {}));
  68650. //# sourceMappingURL=babylon.followCamera.js.map
  68651. "use strict";
  68652. var BABYLON;
  68653. (function (BABYLON) {
  68654. // We're mainly based on the logic defined into the FreeCamera code
  68655. var UniversalCamera = /** @class */ (function (_super) {
  68656. __extends(UniversalCamera, _super);
  68657. //-- end properties for backward compatibility for inputs
  68658. function UniversalCamera(name, position, scene) {
  68659. var _this = _super.call(this, name, position, scene) || this;
  68660. _this.inputs.addGamepad();
  68661. return _this;
  68662. }
  68663. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  68664. //-- Begin properties for backward compatibility for inputs
  68665. get: function () {
  68666. var gamepad = this.inputs.attached["gamepad"];
  68667. if (gamepad)
  68668. return gamepad.gamepadAngularSensibility;
  68669. return 0;
  68670. },
  68671. set: function (value) {
  68672. var gamepad = this.inputs.attached["gamepad"];
  68673. if (gamepad)
  68674. gamepad.gamepadAngularSensibility = value;
  68675. },
  68676. enumerable: true,
  68677. configurable: true
  68678. });
  68679. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  68680. get: function () {
  68681. var gamepad = this.inputs.attached["gamepad"];
  68682. if (gamepad)
  68683. return gamepad.gamepadMoveSensibility;
  68684. return 0;
  68685. },
  68686. set: function (value) {
  68687. var gamepad = this.inputs.attached["gamepad"];
  68688. if (gamepad)
  68689. gamepad.gamepadMoveSensibility = value;
  68690. },
  68691. enumerable: true,
  68692. configurable: true
  68693. });
  68694. UniversalCamera.prototype.getClassName = function () {
  68695. return "UniversalCamera";
  68696. };
  68697. return UniversalCamera;
  68698. }(BABYLON.TouchCamera));
  68699. BABYLON.UniversalCamera = UniversalCamera;
  68700. })(BABYLON || (BABYLON = {}));
  68701. //# sourceMappingURL=babylon.universalCamera.js.map
  68702. "use strict";
  68703. var BABYLON;
  68704. (function (BABYLON) {
  68705. // We're mainly based on the logic defined into the FreeCamera code
  68706. var GamepadCamera = /** @class */ (function (_super) {
  68707. __extends(GamepadCamera, _super);
  68708. //-- end properties for backward compatibility for inputs
  68709. function GamepadCamera(name, position, scene) {
  68710. return _super.call(this, name, position, scene) || this;
  68711. }
  68712. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  68713. //-- Begin properties for backward compatibility for inputs
  68714. get: function () {
  68715. var gamepad = this.inputs.attached["gamepad"];
  68716. if (gamepad)
  68717. return gamepad.gamepadAngularSensibility;
  68718. return 0;
  68719. },
  68720. set: function (value) {
  68721. var gamepad = this.inputs.attached["gamepad"];
  68722. if (gamepad)
  68723. gamepad.gamepadAngularSensibility = value;
  68724. },
  68725. enumerable: true,
  68726. configurable: true
  68727. });
  68728. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  68729. get: function () {
  68730. var gamepad = this.inputs.attached["gamepad"];
  68731. if (gamepad)
  68732. return gamepad.gamepadMoveSensibility;
  68733. return 0;
  68734. },
  68735. set: function (value) {
  68736. var gamepad = this.inputs.attached["gamepad"];
  68737. if (gamepad)
  68738. gamepad.gamepadMoveSensibility = value;
  68739. },
  68740. enumerable: true,
  68741. configurable: true
  68742. });
  68743. GamepadCamera.prototype.getClassName = function () {
  68744. return "GamepadCamera";
  68745. };
  68746. return GamepadCamera;
  68747. }(BABYLON.UniversalCamera));
  68748. BABYLON.GamepadCamera = GamepadCamera;
  68749. })(BABYLON || (BABYLON = {}));
  68750. //# sourceMappingURL=babylon.gamepadCamera.js.map
  68751. "use strict";
  68752. var BABYLON;
  68753. (function (BABYLON) {
  68754. var PostProcessRenderPipelineManager = /** @class */ (function () {
  68755. function PostProcessRenderPipelineManager() {
  68756. this._renderPipelines = {};
  68757. }
  68758. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  68759. this._renderPipelines[renderPipeline._name] = renderPipeline;
  68760. };
  68761. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  68762. if (unique === void 0) { unique = false; }
  68763. var renderPipeline = this._renderPipelines[renderPipelineName];
  68764. if (!renderPipeline) {
  68765. return;
  68766. }
  68767. renderPipeline._attachCameras(cameras, unique);
  68768. };
  68769. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  68770. var renderPipeline = this._renderPipelines[renderPipelineName];
  68771. if (!renderPipeline) {
  68772. return;
  68773. }
  68774. renderPipeline._detachCameras(cameras);
  68775. };
  68776. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  68777. var renderPipeline = this._renderPipelines[renderPipelineName];
  68778. if (!renderPipeline) {
  68779. return;
  68780. }
  68781. renderPipeline._enableEffect(renderEffectName, cameras);
  68782. };
  68783. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  68784. var renderPipeline = this._renderPipelines[renderPipelineName];
  68785. if (!renderPipeline) {
  68786. return;
  68787. }
  68788. renderPipeline._disableEffect(renderEffectName, cameras);
  68789. };
  68790. PostProcessRenderPipelineManager.prototype.update = function () {
  68791. for (var renderPipelineName in this._renderPipelines) {
  68792. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  68793. var pipeline = this._renderPipelines[renderPipelineName];
  68794. if (!pipeline.isSupported) {
  68795. pipeline.dispose();
  68796. delete this._renderPipelines[renderPipelineName];
  68797. }
  68798. else {
  68799. pipeline._update();
  68800. }
  68801. }
  68802. }
  68803. };
  68804. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  68805. for (var renderPipelineName in this._renderPipelines) {
  68806. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  68807. var pipeline = this._renderPipelines[renderPipelineName];
  68808. pipeline._rebuild();
  68809. }
  68810. }
  68811. };
  68812. PostProcessRenderPipelineManager.prototype.dispose = function () {
  68813. for (var renderPipelineName in this._renderPipelines) {
  68814. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  68815. var pipeline = this._renderPipelines[renderPipelineName];
  68816. pipeline.dispose();
  68817. }
  68818. }
  68819. };
  68820. return PostProcessRenderPipelineManager;
  68821. }());
  68822. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  68823. })(BABYLON || (BABYLON = {}));
  68824. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  68825. "use strict";
  68826. var BABYLON;
  68827. (function (BABYLON) {
  68828. /**
  68829. * This represents a set of one or more post processes in Babylon.
  68830. * A post process can be used to apply a shader to a texture after it is rendered.
  68831. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  68832. */
  68833. var PostProcessRenderEffect = /** @class */ (function () {
  68834. /**
  68835. * Instantiates a post process render effect.
  68836. * A post process can be used to apply a shader to a texture after it is rendered.
  68837. * @param engine The engine the effect is tied to
  68838. * @param name The name of the effect
  68839. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  68840. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  68841. */
  68842. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  68843. this._name = name;
  68844. this._singleInstance = singleInstance || true;
  68845. this._getPostProcesses = getPostProcesses;
  68846. this._cameras = {};
  68847. this._indicesForCamera = {};
  68848. this._postProcesses = {};
  68849. }
  68850. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  68851. /**
  68852. * Checks if all the post processes in the effect are supported.
  68853. */
  68854. get: function () {
  68855. for (var index in this._postProcesses) {
  68856. for (var ppIndex in this._postProcesses[index]) {
  68857. if (!this._postProcesses[index][ppIndex].isSupported) {
  68858. return false;
  68859. }
  68860. }
  68861. }
  68862. return true;
  68863. },
  68864. enumerable: true,
  68865. configurable: true
  68866. });
  68867. /**
  68868. * Updates the current state of the effect
  68869. */
  68870. PostProcessRenderEffect.prototype._update = function () {
  68871. };
  68872. /**
  68873. * Attaches the effect on cameras
  68874. * @param cameras The camera to attach to.
  68875. */
  68876. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  68877. var _this = this;
  68878. var cameraKey;
  68879. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68880. if (!cams) {
  68881. return;
  68882. }
  68883. for (var i = 0; i < cams.length; i++) {
  68884. var camera = cams[i];
  68885. var cameraName = camera.name;
  68886. if (this._singleInstance) {
  68887. cameraKey = 0;
  68888. }
  68889. else {
  68890. cameraKey = cameraName;
  68891. }
  68892. if (!this._postProcesses[cameraKey]) {
  68893. var postProcess = this._getPostProcesses();
  68894. if (postProcess) {
  68895. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  68896. }
  68897. }
  68898. if (!this._indicesForCamera[cameraName]) {
  68899. this._indicesForCamera[cameraName] = [];
  68900. }
  68901. this._postProcesses[cameraKey].forEach(function (postProcess) {
  68902. var index = camera.attachPostProcess(postProcess);
  68903. _this._indicesForCamera[cameraName].push(index);
  68904. });
  68905. if (!this._cameras[cameraName]) {
  68906. this._cameras[cameraName] = camera;
  68907. }
  68908. }
  68909. };
  68910. /**
  68911. * Detatches the effect on cameras
  68912. * @param cameras The camera to detatch from.
  68913. */
  68914. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  68915. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68916. if (!cams) {
  68917. return;
  68918. }
  68919. for (var i = 0; i < cams.length; i++) {
  68920. var camera = cams[i];
  68921. var cameraName = camera.name;
  68922. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68923. camera.detachPostProcess(postProcess);
  68924. });
  68925. if (this._cameras[cameraName]) {
  68926. //this._indicesForCamera.splice(index, 1);
  68927. this._cameras[cameraName] = null;
  68928. }
  68929. }
  68930. };
  68931. /**
  68932. * Enables the effect on given cameras
  68933. * @param cameras The camera to enable.
  68934. */
  68935. PostProcessRenderEffect.prototype._enable = function (cameras) {
  68936. var _this = this;
  68937. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68938. if (!cams) {
  68939. return;
  68940. }
  68941. for (var i = 0; i < cams.length; i++) {
  68942. var camera = cams[i];
  68943. var cameraName = camera.name;
  68944. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  68945. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  68946. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68947. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  68948. });
  68949. }
  68950. }
  68951. }
  68952. };
  68953. /**
  68954. * Disables the effect on the given cameras
  68955. * @param cameras The camera to disable.
  68956. */
  68957. PostProcessRenderEffect.prototype._disable = function (cameras) {
  68958. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68959. if (!cams) {
  68960. return;
  68961. }
  68962. for (var i = 0; i < cams.length; i++) {
  68963. var camera = cams[i];
  68964. var cameraName = camera.name;
  68965. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68966. camera.detachPostProcess(postProcess);
  68967. });
  68968. }
  68969. };
  68970. /**
  68971. * Gets a list of the post processes contained in the effect.
  68972. * @param camera The camera to get the post processes on.
  68973. * @returns The list of the post processes in the effect.
  68974. */
  68975. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  68976. if (this._singleInstance) {
  68977. return this._postProcesses[0];
  68978. }
  68979. else {
  68980. if (!camera) {
  68981. return null;
  68982. }
  68983. return this._postProcesses[camera.name];
  68984. }
  68985. };
  68986. return PostProcessRenderEffect;
  68987. }());
  68988. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  68989. })(BABYLON || (BABYLON = {}));
  68990. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  68991. "use strict";
  68992. var BABYLON;
  68993. (function (BABYLON) {
  68994. var PostProcessRenderPipeline = /** @class */ (function () {
  68995. function PostProcessRenderPipeline(engine, name) {
  68996. this.engine = engine;
  68997. this._name = name;
  68998. this._renderEffects = {};
  68999. this._renderEffectsForIsolatedPass = new Array();
  69000. this._cameras = [];
  69001. }
  69002. PostProcessRenderPipeline.prototype.getClassName = function () {
  69003. return "PostProcessRenderPipeline";
  69004. };
  69005. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  69006. get: function () {
  69007. for (var renderEffectName in this._renderEffects) {
  69008. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  69009. if (!this._renderEffects[renderEffectName].isSupported) {
  69010. return false;
  69011. }
  69012. }
  69013. }
  69014. return true;
  69015. },
  69016. enumerable: true,
  69017. configurable: true
  69018. });
  69019. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  69020. this._renderEffects[renderEffect._name] = renderEffect;
  69021. };
  69022. // private
  69023. PostProcessRenderPipeline.prototype._rebuild = function () {
  69024. };
  69025. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  69026. var renderEffects = this._renderEffects[renderEffectName];
  69027. if (!renderEffects) {
  69028. return;
  69029. }
  69030. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  69031. };
  69032. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  69033. var renderEffects = this._renderEffects[renderEffectName];
  69034. if (!renderEffects) {
  69035. return;
  69036. }
  69037. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  69038. };
  69039. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  69040. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  69041. if (!cams) {
  69042. return;
  69043. }
  69044. var indicesToDelete = [];
  69045. var i;
  69046. for (i = 0; i < cams.length; i++) {
  69047. var camera = cams[i];
  69048. var cameraName = camera.name;
  69049. if (this._cameras.indexOf(camera) === -1) {
  69050. this._cameras[cameraName] = camera;
  69051. }
  69052. else if (unique) {
  69053. indicesToDelete.push(i);
  69054. }
  69055. }
  69056. for (i = 0; i < indicesToDelete.length; i++) {
  69057. cameras.splice(indicesToDelete[i], 1);
  69058. }
  69059. for (var renderEffectName in this._renderEffects) {
  69060. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  69061. this._renderEffects[renderEffectName]._attachCameras(cams);
  69062. }
  69063. }
  69064. };
  69065. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  69066. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  69067. if (!cams) {
  69068. return;
  69069. }
  69070. for (var renderEffectName in this._renderEffects) {
  69071. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  69072. this._renderEffects[renderEffectName]._detachCameras(cams);
  69073. }
  69074. }
  69075. for (var i = 0; i < cams.length; i++) {
  69076. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  69077. }
  69078. };
  69079. PostProcessRenderPipeline.prototype._update = function () {
  69080. for (var renderEffectName in this._renderEffects) {
  69081. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  69082. this._renderEffects[renderEffectName]._update();
  69083. }
  69084. }
  69085. for (var i = 0; i < this._cameras.length; i++) {
  69086. var cameraName = this._cameras[i].name;
  69087. if (this._renderEffectsForIsolatedPass[cameraName]) {
  69088. this._renderEffectsForIsolatedPass[cameraName]._update();
  69089. }
  69090. }
  69091. };
  69092. PostProcessRenderPipeline.prototype._reset = function () {
  69093. this._renderEffects = {};
  69094. this._renderEffectsForIsolatedPass = new Array();
  69095. };
  69096. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  69097. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  69098. var effectKeys = Object.keys(this._renderEffects);
  69099. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  69100. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  69101. if (postProcesses) {
  69102. postProcesses[0].samples = sampleCount;
  69103. return true;
  69104. }
  69105. }
  69106. return false;
  69107. };
  69108. PostProcessRenderPipeline.prototype.dispose = function () {
  69109. // Must be implemented by children
  69110. };
  69111. __decorate([
  69112. BABYLON.serialize()
  69113. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  69114. return PostProcessRenderPipeline;
  69115. }());
  69116. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  69117. })(BABYLON || (BABYLON = {}));
  69118. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  69119. "use strict";
  69120. var BABYLON;
  69121. (function (BABYLON) {
  69122. /**
  69123. * This represents a depth renderer in Babylon.
  69124. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  69125. */
  69126. var DepthRenderer = /** @class */ (function () {
  69127. /**
  69128. * Instantiates a depth renderer
  69129. * @param scene The scene the renderer belongs to
  69130. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  69131. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  69132. */
  69133. function DepthRenderer(scene, type, camera) {
  69134. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  69135. if (camera === void 0) { camera = null; }
  69136. var _this = this;
  69137. this._scene = scene;
  69138. this._camera = camera;
  69139. var engine = scene.getEngine();
  69140. // Render target
  69141. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  69142. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69143. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69144. this._depthMap.refreshRate = 1;
  69145. this._depthMap.renderParticles = false;
  69146. this._depthMap.renderList = null;
  69147. // Camera to get depth map from to support multiple concurrent cameras
  69148. this._depthMap.activeCamera = this._camera;
  69149. this._depthMap.ignoreCameraViewport = true;
  69150. this._depthMap.useCameraPostProcesses = false;
  69151. // set default depth value to 1.0 (far away)
  69152. this._depthMap.onClearObservable.add(function (engine) {
  69153. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  69154. });
  69155. // Custom render function
  69156. var renderSubMesh = function (subMesh) {
  69157. var mesh = subMesh.getRenderingMesh();
  69158. var scene = _this._scene;
  69159. var engine = scene.getEngine();
  69160. var material = subMesh.getMaterial();
  69161. if (!material) {
  69162. return;
  69163. }
  69164. // Culling and reverse (right handed system)
  69165. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69166. // Managing instances
  69167. var batch = mesh._getInstancesRenderList(subMesh._id);
  69168. if (batch.mustReturn) {
  69169. return;
  69170. }
  69171. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69172. var camera = _this._camera || scene.activeCamera;
  69173. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  69174. engine.enableEffect(_this._effect);
  69175. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69176. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69177. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  69178. // Alpha test
  69179. if (material && material.needAlphaTesting()) {
  69180. var alphaTexture = material.getAlphaTestTexture();
  69181. if (alphaTexture) {
  69182. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69183. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69184. }
  69185. }
  69186. // Bones
  69187. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69188. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69189. }
  69190. // Draw
  69191. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69192. }
  69193. };
  69194. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69195. var index;
  69196. if (depthOnlySubMeshes.length) {
  69197. engine.setColorWrite(false);
  69198. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69199. renderSubMesh(depthOnlySubMeshes.data[index]);
  69200. }
  69201. engine.setColorWrite(true);
  69202. }
  69203. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69204. renderSubMesh(opaqueSubMeshes.data[index]);
  69205. }
  69206. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69207. renderSubMesh(alphaTestSubMeshes.data[index]);
  69208. }
  69209. };
  69210. }
  69211. /**
  69212. * Creates the depth rendering effect and checks if the effect is ready.
  69213. * @param subMesh The submesh to be used to render the depth map of
  69214. * @param useInstances If multiple world instances should be used
  69215. * @returns if the depth renderer is ready to render the depth map
  69216. */
  69217. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  69218. var material = subMesh.getMaterial();
  69219. if (material.disableDepthWrite) {
  69220. return false;
  69221. }
  69222. var defines = [];
  69223. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69224. var mesh = subMesh.getMesh();
  69225. // Alpha test
  69226. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  69227. defines.push("#define ALPHATEST");
  69228. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69229. attribs.push(BABYLON.VertexBuffer.UVKind);
  69230. defines.push("#define UV1");
  69231. }
  69232. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69233. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69234. defines.push("#define UV2");
  69235. }
  69236. }
  69237. // Bones
  69238. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69239. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69240. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69241. if (mesh.numBoneInfluencers > 4) {
  69242. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69243. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69244. }
  69245. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69246. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69247. }
  69248. else {
  69249. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69250. }
  69251. // Instances
  69252. if (useInstances) {
  69253. defines.push("#define INSTANCES");
  69254. attribs.push("world0");
  69255. attribs.push("world1");
  69256. attribs.push("world2");
  69257. attribs.push("world3");
  69258. }
  69259. // Get correct effect
  69260. var join = defines.join("\n");
  69261. if (this._cachedDefines !== join) {
  69262. this._cachedDefines = join;
  69263. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  69264. }
  69265. return this._effect.isReady();
  69266. };
  69267. /**
  69268. * Gets the texture which the depth map will be written to.
  69269. * @returns The depth map texture
  69270. */
  69271. DepthRenderer.prototype.getDepthMap = function () {
  69272. return this._depthMap;
  69273. };
  69274. /**
  69275. * Disposes of the depth renderer.
  69276. */
  69277. DepthRenderer.prototype.dispose = function () {
  69278. this._depthMap.dispose();
  69279. };
  69280. return DepthRenderer;
  69281. }());
  69282. BABYLON.DepthRenderer = DepthRenderer;
  69283. })(BABYLON || (BABYLON = {}));
  69284. //# sourceMappingURL=babylon.depthRenderer.js.map
  69285. "use strict";
  69286. var BABYLON;
  69287. (function (BABYLON) {
  69288. var SSAORenderingPipeline = /** @class */ (function (_super) {
  69289. __extends(SSAORenderingPipeline, _super);
  69290. /**
  69291. * @constructor
  69292. * @param {string} name - The rendering pipeline name
  69293. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69294. * @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 }
  69295. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69296. */
  69297. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  69298. var _this = _super.call(this, scene.getEngine(), name) || this;
  69299. // Members
  69300. /**
  69301. * The PassPostProcess id in the pipeline that contains the original scene color
  69302. */
  69303. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  69304. /**
  69305. * The SSAO PostProcess id in the pipeline
  69306. */
  69307. _this.SSAORenderEffect = "SSAORenderEffect";
  69308. /**
  69309. * The horizontal blur PostProcess id in the pipeline
  69310. */
  69311. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  69312. /**
  69313. * The vertical blur PostProcess id in the pipeline
  69314. */
  69315. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  69316. /**
  69317. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  69318. */
  69319. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  69320. /**
  69321. * The output strength of the SSAO post-process. Default value is 1.0.
  69322. */
  69323. _this.totalStrength = 1.0;
  69324. /**
  69325. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  69326. */
  69327. _this.radius = 0.0001;
  69328. /**
  69329. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  69330. * Must not be equal to fallOff and superior to fallOff.
  69331. * Default value is 0.975
  69332. */
  69333. _this.area = 0.0075;
  69334. /**
  69335. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  69336. * Must not be equal to area and inferior to area.
  69337. * Default value is 0.0
  69338. */
  69339. _this.fallOff = 0.000001;
  69340. /**
  69341. * The base color of the SSAO post-process
  69342. * The final result is "base + ssao" between [0, 1]
  69343. */
  69344. _this.base = 0.5;
  69345. _this._firstUpdate = true;
  69346. _this._scene = scene;
  69347. // Set up assets
  69348. _this._createRandomTexture();
  69349. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  69350. var ssaoRatio = ratio.ssaoRatio || ratio;
  69351. var combineRatio = ratio.combineRatio || ratio;
  69352. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  69353. _this._createSSAOPostProcess(ssaoRatio);
  69354. _this._createBlurPostProcess(ssaoRatio);
  69355. _this._createSSAOCombinePostProcess(combineRatio);
  69356. // Set up pipeline
  69357. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  69358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  69359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  69360. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  69361. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  69362. // Finish
  69363. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69364. if (cameras)
  69365. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  69366. return _this;
  69367. }
  69368. // Public Methods
  69369. /**
  69370. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  69371. */
  69372. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69373. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69374. for (var i = 0; i < this._scene.cameras.length; i++) {
  69375. var camera = this._scene.cameras[i];
  69376. this._originalColorPostProcess.dispose(camera);
  69377. this._ssaoPostProcess.dispose(camera);
  69378. this._blurHPostProcess.dispose(camera);
  69379. this._blurVPostProcess.dispose(camera);
  69380. this._ssaoCombinePostProcess.dispose(camera);
  69381. }
  69382. this._randomTexture.dispose();
  69383. if (disableDepthRender)
  69384. this._scene.disableDepthRenderer();
  69385. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69386. _super.prototype.dispose.call(this);
  69387. };
  69388. // Private Methods
  69389. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  69390. var _this = this;
  69391. var size = 16;
  69392. 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);
  69393. 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);
  69394. this._blurHPostProcess.onActivateObservable.add(function () {
  69395. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  69396. _this._blurHPostProcess.kernel = size * dw;
  69397. });
  69398. this._blurVPostProcess.onActivateObservable.add(function () {
  69399. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  69400. _this._blurVPostProcess.kernel = size * dw;
  69401. });
  69402. };
  69403. SSAORenderingPipeline.prototype._rebuild = function () {
  69404. this._firstUpdate = true;
  69405. _super.prototype._rebuild.call(this);
  69406. };
  69407. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  69408. var _this = this;
  69409. var numSamples = 16;
  69410. var sampleSphere = [
  69411. 0.5381, 0.1856, -0.4319,
  69412. 0.1379, 0.2486, 0.4430,
  69413. 0.3371, 0.5679, -0.0057,
  69414. -0.6999, -0.0451, -0.0019,
  69415. 0.0689, -0.1598, -0.8547,
  69416. 0.0560, 0.0069, -0.1843,
  69417. -0.0146, 0.1402, 0.0762,
  69418. 0.0100, -0.1924, -0.0344,
  69419. -0.3577, -0.5301, -0.4358,
  69420. -0.3169, 0.1063, 0.0158,
  69421. 0.0103, -0.5869, 0.0046,
  69422. -0.0897, -0.4940, 0.3287,
  69423. 0.7119, -0.0154, -0.0918,
  69424. -0.0533, 0.0596, -0.5411,
  69425. 0.0352, -0.0631, 0.5460,
  69426. -0.4776, 0.2847, -0.0271
  69427. ];
  69428. var samplesFactor = 1.0 / numSamples;
  69429. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  69430. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  69431. "area", "fallOff", "base", "range", "viewport"
  69432. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  69433. this._ssaoPostProcess.onApply = function (effect) {
  69434. if (_this._firstUpdate) {
  69435. effect.setArray3("sampleSphere", sampleSphere);
  69436. effect.setFloat("samplesFactor", samplesFactor);
  69437. effect.setFloat("randTextureTiles", 4.0);
  69438. }
  69439. effect.setFloat("totalStrength", _this.totalStrength);
  69440. effect.setFloat("radius", _this.radius);
  69441. effect.setFloat("area", _this.area);
  69442. effect.setFloat("fallOff", _this.fallOff);
  69443. effect.setFloat("base", _this.base);
  69444. effect.setTexture("textureSampler", _this._depthTexture);
  69445. effect.setTexture("randomSampler", _this._randomTexture);
  69446. };
  69447. };
  69448. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  69449. var _this = this;
  69450. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69451. this._ssaoCombinePostProcess.onApply = function (effect) {
  69452. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  69453. };
  69454. };
  69455. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  69456. var size = 512;
  69457. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69458. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69459. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69460. var context = this._randomTexture.getContext();
  69461. var rand = function (min, max) {
  69462. return Math.random() * (max - min) + min;
  69463. };
  69464. var randVector = BABYLON.Vector3.Zero();
  69465. for (var x = 0; x < size; x++) {
  69466. for (var y = 0; y < size; y++) {
  69467. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  69468. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  69469. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  69470. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  69471. context.fillRect(x, y, 1, 1);
  69472. }
  69473. }
  69474. this._randomTexture.update(false);
  69475. };
  69476. __decorate([
  69477. BABYLON.serialize()
  69478. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  69479. __decorate([
  69480. BABYLON.serialize()
  69481. ], SSAORenderingPipeline.prototype, "radius", void 0);
  69482. __decorate([
  69483. BABYLON.serialize()
  69484. ], SSAORenderingPipeline.prototype, "area", void 0);
  69485. __decorate([
  69486. BABYLON.serialize()
  69487. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  69488. __decorate([
  69489. BABYLON.serialize()
  69490. ], SSAORenderingPipeline.prototype, "base", void 0);
  69491. return SSAORenderingPipeline;
  69492. }(BABYLON.PostProcessRenderPipeline));
  69493. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  69494. })(BABYLON || (BABYLON = {}));
  69495. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  69496. "use strict";
  69497. var BABYLON;
  69498. (function (BABYLON) {
  69499. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  69500. __extends(SSAO2RenderingPipeline, _super);
  69501. /**
  69502. * @constructor
  69503. * @param {string} name - The rendering pipeline name
  69504. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69505. * @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 }
  69506. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69507. */
  69508. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  69509. var _this = _super.call(this, scene.getEngine(), name) || this;
  69510. // Members
  69511. /**
  69512. * The PassPostProcess id in the pipeline that contains the original scene color
  69513. */
  69514. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  69515. /**
  69516. * The SSAO PostProcess id in the pipeline
  69517. */
  69518. _this.SSAORenderEffect = "SSAORenderEffect";
  69519. /**
  69520. * The horizontal blur PostProcess id in the pipeline
  69521. */
  69522. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  69523. /**
  69524. * The vertical blur PostProcess id in the pipeline
  69525. */
  69526. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  69527. /**
  69528. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  69529. */
  69530. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  69531. /**
  69532. * The output strength of the SSAO post-process. Default value is 1.0.
  69533. */
  69534. _this.totalStrength = 1.0;
  69535. /**
  69536. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  69537. */
  69538. _this.maxZ = 100.0;
  69539. /**
  69540. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  69541. */
  69542. _this.minZAspect = 0.2;
  69543. /**
  69544. * Number of samples used for the SSAO calculations. Default value is 8
  69545. */
  69546. _this._samples = 8;
  69547. /**
  69548. * Are we using bilateral blur ?
  69549. */
  69550. _this._expensiveBlur = true;
  69551. /**
  69552. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  69553. */
  69554. _this.radius = 2.0;
  69555. /**
  69556. * The base color of the SSAO post-process
  69557. * The final result is "base + ssao" between [0, 1]
  69558. */
  69559. _this.base = 0.1;
  69560. _this._firstUpdate = true;
  69561. _this._scene = scene;
  69562. if (!_this.isSupported) {
  69563. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  69564. return _this;
  69565. }
  69566. var ssaoRatio = ratio.ssaoRatio || ratio;
  69567. var blurRatio = ratio.blurRatio || ratio;
  69568. // Set up assets
  69569. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  69570. _this._createRandomTexture();
  69571. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  69572. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  69573. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  69574. _this._createSSAOPostProcess(1.0);
  69575. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  69576. _this._createSSAOCombinePostProcess(blurRatio);
  69577. // Set up pipeline
  69578. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  69579. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  69580. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  69581. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  69582. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  69583. // Finish
  69584. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69585. if (cameras)
  69586. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  69587. return _this;
  69588. }
  69589. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  69590. get: function () {
  69591. return this._samples;
  69592. },
  69593. set: function (n) {
  69594. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  69595. this._samples = n;
  69596. this._sampleSphere = this._generateHemisphere();
  69597. this._firstUpdate = true;
  69598. },
  69599. enumerable: true,
  69600. configurable: true
  69601. });
  69602. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  69603. get: function () {
  69604. return this._expensiveBlur;
  69605. },
  69606. set: function (b) {
  69607. 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"]);
  69608. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  69609. this._expensiveBlur = b;
  69610. this._firstUpdate = true;
  69611. },
  69612. enumerable: true,
  69613. configurable: true
  69614. });
  69615. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  69616. /**
  69617. * Support test.
  69618. */
  69619. get: function () {
  69620. var engine = BABYLON.Engine.LastCreatedEngine;
  69621. if (!engine) {
  69622. return false;
  69623. }
  69624. return engine.getCaps().drawBuffersExtension;
  69625. },
  69626. enumerable: true,
  69627. configurable: true
  69628. });
  69629. // Public Methods
  69630. /**
  69631. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  69632. */
  69633. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  69634. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  69635. for (var i = 0; i < this._scene.cameras.length; i++) {
  69636. var camera = this._scene.cameras[i];
  69637. this._originalColorPostProcess.dispose(camera);
  69638. this._ssaoPostProcess.dispose(camera);
  69639. this._blurHPostProcess.dispose(camera);
  69640. this._blurVPostProcess.dispose(camera);
  69641. this._ssaoCombinePostProcess.dispose(camera);
  69642. }
  69643. this._randomTexture.dispose();
  69644. if (disableGeometryBufferRenderer)
  69645. this._scene.disableGeometryBufferRenderer();
  69646. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69647. _super.prototype.dispose.call(this);
  69648. };
  69649. // Private Methods
  69650. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  69651. var _this = this;
  69652. this._samplerOffsets = [];
  69653. var expensive = this.expensiveBlur;
  69654. for (var i = -8; i < 8; i++) {
  69655. this._samplerOffsets.push(i * 2 + 0.5);
  69656. }
  69657. 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");
  69658. this._blurHPostProcess.onApply = function (effect) {
  69659. if (!_this._scene.activeCamera) {
  69660. return;
  69661. }
  69662. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  69663. effect.setFloat("near", _this._scene.activeCamera.minZ);
  69664. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  69665. effect.setFloat("radius", _this.radius);
  69666. effect.setTexture("depthSampler", _this._depthTexture);
  69667. if (_this._firstUpdate) {
  69668. effect.setArray("samplerOffsets", _this._samplerOffsets);
  69669. }
  69670. };
  69671. 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");
  69672. this._blurVPostProcess.onApply = function (effect) {
  69673. if (!_this._scene.activeCamera) {
  69674. return;
  69675. }
  69676. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  69677. effect.setFloat("near", _this._scene.activeCamera.minZ);
  69678. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  69679. effect.setFloat("radius", _this.radius);
  69680. effect.setTexture("depthSampler", _this._depthTexture);
  69681. if (_this._firstUpdate) {
  69682. effect.setArray("samplerOffsets", _this._samplerOffsets);
  69683. _this._firstUpdate = false;
  69684. }
  69685. };
  69686. };
  69687. SSAO2RenderingPipeline.prototype._rebuild = function () {
  69688. this._firstUpdate = true;
  69689. _super.prototype._rebuild.call(this);
  69690. };
  69691. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  69692. var numSamples = this.samples;
  69693. var result = [];
  69694. var vector, scale;
  69695. var rand = function (min, max) {
  69696. return Math.random() * (max - min) + min;
  69697. };
  69698. var i = 0;
  69699. while (i < numSamples) {
  69700. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  69701. vector.normalize();
  69702. scale = i / numSamples;
  69703. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  69704. vector.scaleInPlace(scale);
  69705. result.push(vector.x, vector.y, vector.z);
  69706. i++;
  69707. }
  69708. return result;
  69709. };
  69710. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  69711. var _this = this;
  69712. var numSamples = this.samples;
  69713. this._sampleSphere = this._generateHemisphere();
  69714. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  69715. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  69716. "base", "range", "projection", "near", "far", "texelSize",
  69717. "xViewport", "yViewport", "maxZ", "minZAspect"
  69718. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  69719. this._ssaoPostProcess.onApply = function (effect) {
  69720. if (_this._firstUpdate) {
  69721. effect.setArray3("sampleSphere", _this._sampleSphere);
  69722. effect.setFloat("randTextureTiles", 4.0);
  69723. }
  69724. if (!_this._scene.activeCamera) {
  69725. return;
  69726. }
  69727. effect.setFloat("samplesFactor", 1 / _this.samples);
  69728. effect.setFloat("totalStrength", _this.totalStrength);
  69729. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  69730. effect.setFloat("radius", _this.radius);
  69731. effect.setFloat("maxZ", _this.maxZ);
  69732. effect.setFloat("minZAspect", _this.minZAspect);
  69733. effect.setFloat("base", _this.base);
  69734. effect.setFloat("near", _this._scene.activeCamera.minZ);
  69735. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  69736. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  69737. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  69738. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  69739. effect.setTexture("textureSampler", _this._depthTexture);
  69740. effect.setTexture("normalSampler", _this._normalTexture);
  69741. effect.setTexture("randomSampler", _this._randomTexture);
  69742. };
  69743. };
  69744. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  69745. var _this = this;
  69746. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69747. this._ssaoCombinePostProcess.onApply = function (effect) {
  69748. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  69749. };
  69750. };
  69751. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  69752. var size = 512;
  69753. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69754. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69755. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69756. var context = this._randomTexture.getContext();
  69757. var rand = function (min, max) {
  69758. return Math.random() * (max - min) + min;
  69759. };
  69760. var randVector = BABYLON.Vector3.Zero();
  69761. for (var x = 0; x < size; x++) {
  69762. for (var y = 0; y < size; y++) {
  69763. randVector.x = rand(0.0, 1.0);
  69764. randVector.y = rand(0.0, 1.0);
  69765. randVector.z = 0.0;
  69766. randVector.normalize();
  69767. randVector.scaleInPlace(255);
  69768. randVector.x = Math.floor(randVector.x);
  69769. randVector.y = Math.floor(randVector.y);
  69770. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  69771. context.fillRect(x, y, 1, 1);
  69772. }
  69773. }
  69774. this._randomTexture.update(false);
  69775. };
  69776. __decorate([
  69777. BABYLON.serialize()
  69778. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  69779. __decorate([
  69780. BABYLON.serialize()
  69781. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  69782. __decorate([
  69783. BABYLON.serialize()
  69784. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  69785. __decorate([
  69786. BABYLON.serialize("samples")
  69787. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  69788. __decorate([
  69789. BABYLON.serialize("expensiveBlur")
  69790. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  69791. __decorate([
  69792. BABYLON.serialize()
  69793. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  69794. __decorate([
  69795. BABYLON.serialize()
  69796. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  69797. return SSAO2RenderingPipeline;
  69798. }(BABYLON.PostProcessRenderPipeline));
  69799. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  69800. })(BABYLON || (BABYLON = {}));
  69801. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  69802. "use strict";
  69803. // BABYLON.JS Chromatic Aberration GLSL Shader
  69804. // Author: Olivier Guyot
  69805. // Separates very slightly R, G and B colors on the edges of the screen
  69806. // Inspired by Francois Tarlier & Martins Upitis
  69807. var BABYLON;
  69808. (function (BABYLON) {
  69809. var LensRenderingPipeline = /** @class */ (function (_super) {
  69810. __extends(LensRenderingPipeline, _super);
  69811. /**
  69812. * @constructor
  69813. *
  69814. * Effect parameters are as follow:
  69815. * {
  69816. * chromatic_aberration: number; // from 0 to x (1 for realism)
  69817. * edge_blur: number; // from 0 to x (1 for realism)
  69818. * distortion: number; // from 0 to x (1 for realism)
  69819. * grain_amount: number; // from 0 to 1
  69820. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  69821. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  69822. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  69823. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  69824. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  69825. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  69826. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  69827. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  69828. * }
  69829. * Note: if an effect parameter is unset, effect is disabled
  69830. *
  69831. * @param {string} name - The rendering pipeline name
  69832. * @param {object} parameters - An object containing all parameters (see above)
  69833. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69834. * @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)
  69835. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69836. */
  69837. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  69838. if (ratio === void 0) { ratio = 1.0; }
  69839. var _this = _super.call(this, scene.getEngine(), name) || this;
  69840. // Lens effects can be of the following:
  69841. // - chromatic aberration (slight shift of RGB colors)
  69842. // - blur on the edge of the lens
  69843. // - lens distortion
  69844. // - depth-of-field blur & highlights enhancing
  69845. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  69846. // - grain effect (noise or custom texture)
  69847. // Two additional texture samplers are needed:
  69848. // - depth map (for depth-of-field)
  69849. // - grain texture
  69850. /**
  69851. * The chromatic aberration PostProcess id in the pipeline
  69852. */
  69853. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  69854. /**
  69855. * The highlights enhancing PostProcess id in the pipeline
  69856. */
  69857. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  69858. /**
  69859. * The depth-of-field PostProcess id in the pipeline
  69860. */
  69861. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  69862. _this._scene = scene;
  69863. // Fetch texture samplers
  69864. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  69865. if (parameters.grain_texture) {
  69866. _this._grainTexture = parameters.grain_texture;
  69867. }
  69868. else {
  69869. _this._createGrainTexture();
  69870. }
  69871. // save parameters
  69872. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  69873. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  69874. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  69875. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  69876. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  69877. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  69878. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  69879. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  69880. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  69881. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  69882. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  69883. // Create effects
  69884. _this._createChromaticAberrationPostProcess(ratio);
  69885. _this._createHighlightsPostProcess(ratio);
  69886. _this._createDepthOfFieldPostProcess(ratio / 4);
  69887. // Set up pipeline
  69888. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  69889. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  69890. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  69891. if (_this._highlightsGain === -1) {
  69892. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  69893. }
  69894. // Finish
  69895. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69896. if (cameras) {
  69897. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  69898. }
  69899. return _this;
  69900. }
  69901. // public methods (self explanatory)
  69902. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  69903. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  69904. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  69905. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  69906. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  69907. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  69908. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  69909. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  69910. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  69911. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  69912. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  69913. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  69914. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  69915. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  69916. };
  69917. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  69918. this._highlightsPostProcess.updateEffect();
  69919. };
  69920. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  69921. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  69922. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  69923. this._highlightsGain = amount;
  69924. };
  69925. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  69926. if (this._highlightsGain === -1) {
  69927. this._highlightsGain = 1.0;
  69928. }
  69929. this._highlightsThreshold = amount;
  69930. };
  69931. LensRenderingPipeline.prototype.disableHighlights = function () {
  69932. this._highlightsGain = -1;
  69933. };
  69934. /**
  69935. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  69936. */
  69937. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69938. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69939. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69940. this._chromaticAberrationPostProcess = null;
  69941. this._highlightsPostProcess = null;
  69942. this._depthOfFieldPostProcess = null;
  69943. this._grainTexture.dispose();
  69944. if (disableDepthRender)
  69945. this._scene.disableDepthRenderer();
  69946. };
  69947. // colors shifting and distortion
  69948. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  69949. var _this = this;
  69950. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  69951. [], // samplers
  69952. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69953. this._chromaticAberrationPostProcess.onApply = function (effect) {
  69954. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  69955. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69956. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69957. effect.setFloat('radialIntensity', 1);
  69958. effect.setFloat2('direction', 17, 17);
  69959. effect.setFloat2('centerPosition', 0.5, 0.5);
  69960. };
  69961. };
  69962. // highlights enhancing
  69963. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  69964. var _this = this;
  69965. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  69966. [], // samplers
  69967. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  69968. this._highlightsPostProcess.onApply = function (effect) {
  69969. effect.setFloat('gain', _this._highlightsGain);
  69970. effect.setFloat('threshold', _this._highlightsThreshold);
  69971. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  69972. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69973. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69974. };
  69975. };
  69976. // colors shifting and distortion
  69977. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  69978. var _this = this;
  69979. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  69980. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  69981. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  69982. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69983. this._depthOfFieldPostProcess.onApply = function (effect) {
  69984. effect.setTexture("depthSampler", _this._depthTexture);
  69985. effect.setTexture("grainSampler", _this._grainTexture);
  69986. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69987. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69988. effect.setFloat('grain_amount', _this._grainAmount);
  69989. effect.setBool('blur_noise', _this._blurNoise);
  69990. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69991. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69992. effect.setFloat('distortion', _this._distortion);
  69993. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69994. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69995. effect.setFloat('aperture', _this._dofAperture);
  69996. effect.setFloat('darken', _this._dofDarken);
  69997. effect.setFloat('edge_blur', _this._edgeBlur);
  69998. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69999. if (_this._scene.activeCamera) {
  70000. effect.setFloat('near', _this._scene.activeCamera.minZ);
  70001. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  70002. }
  70003. };
  70004. };
  70005. // creates a black and white random noise texture, 512x512
  70006. LensRenderingPipeline.prototype._createGrainTexture = function () {
  70007. var size = 512;
  70008. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70009. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  70010. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  70011. var context = this._grainTexture.getContext();
  70012. var rand = function (min, max) {
  70013. return Math.random() * (max - min) + min;
  70014. };
  70015. var value;
  70016. for (var x = 0; x < size; x++) {
  70017. for (var y = 0; y < size; y++) {
  70018. value = Math.floor(rand(0.42, 0.58) * 255);
  70019. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  70020. context.fillRect(x, y, 1, 1);
  70021. }
  70022. }
  70023. this._grainTexture.update(false);
  70024. };
  70025. return LensRenderingPipeline;
  70026. }(BABYLON.PostProcessRenderPipeline));
  70027. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  70028. })(BABYLON || (BABYLON = {}));
  70029. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  70030. "use strict";
  70031. var BABYLON;
  70032. (function (BABYLON) {
  70033. var StandardRenderingPipeline = /** @class */ (function (_super) {
  70034. __extends(StandardRenderingPipeline, _super);
  70035. /**
  70036. * @constructor
  70037. * @param {string} name - The rendering pipeline name
  70038. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70039. * @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)
  70040. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  70041. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70042. */
  70043. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  70044. if (originalPostProcess === void 0) { originalPostProcess = null; }
  70045. var _this = _super.call(this, scene.getEngine(), name) || this;
  70046. _this.downSampleX4PostProcess = null;
  70047. _this.brightPassPostProcess = null;
  70048. _this.blurHPostProcesses = [];
  70049. _this.blurVPostProcesses = [];
  70050. _this.textureAdderPostProcess = null;
  70051. _this.volumetricLightPostProcess = null;
  70052. _this.volumetricLightSmoothXPostProcess = null;
  70053. _this.volumetricLightSmoothYPostProcess = null;
  70054. _this.volumetricLightMergePostProces = null;
  70055. _this.volumetricLightFinalPostProcess = null;
  70056. _this.luminancePostProcess = null;
  70057. _this.luminanceDownSamplePostProcesses = [];
  70058. _this.hdrPostProcess = null;
  70059. _this.textureAdderFinalPostProcess = null;
  70060. _this.lensFlareFinalPostProcess = null;
  70061. _this.hdrFinalPostProcess = null;
  70062. _this.lensFlarePostProcess = null;
  70063. _this.lensFlareComposePostProcess = null;
  70064. _this.motionBlurPostProcess = null;
  70065. _this.depthOfFieldPostProcess = null;
  70066. // Values
  70067. _this.brightThreshold = 1.0;
  70068. _this.blurWidth = 512.0;
  70069. _this.horizontalBlur = false;
  70070. _this.exposure = 1.0;
  70071. _this.lensTexture = null;
  70072. _this.volumetricLightCoefficient = 0.2;
  70073. _this.volumetricLightPower = 4.0;
  70074. _this.volumetricLightBlurScale = 64.0;
  70075. _this.sourceLight = null;
  70076. _this.hdrMinimumLuminance = 1.0;
  70077. _this.hdrDecreaseRate = 0.5;
  70078. _this.hdrIncreaseRate = 0.5;
  70079. _this.lensColorTexture = null;
  70080. _this.lensFlareStrength = 20.0;
  70081. _this.lensFlareGhostDispersal = 1.4;
  70082. _this.lensFlareHaloWidth = 0.7;
  70083. _this.lensFlareDistortionStrength = 16.0;
  70084. _this.lensStarTexture = null;
  70085. _this.lensFlareDirtTexture = null;
  70086. _this.depthOfFieldDistance = 10.0;
  70087. _this.depthOfFieldBlurWidth = 64.0;
  70088. _this.motionStrength = 1.0;
  70089. // IAnimatable
  70090. _this.animations = [];
  70091. _this._currentDepthOfFieldSource = null;
  70092. _this._hdrCurrentLuminance = 1.0;
  70093. // Getters and setters
  70094. _this._bloomEnabled = true;
  70095. _this._depthOfFieldEnabled = false;
  70096. _this._vlsEnabled = false;
  70097. _this._lensFlareEnabled = false;
  70098. _this._hdrEnabled = false;
  70099. _this._motionBlurEnabled = false;
  70100. _this._motionBlurSamples = 64.0;
  70101. _this._volumetricLightStepsCount = 50.0;
  70102. _this._cameras = cameras || [];
  70103. // Initialize
  70104. _this._scene = scene;
  70105. _this._basePostProcess = originalPostProcess;
  70106. _this._ratio = ratio;
  70107. // Misc
  70108. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70109. // Finish
  70110. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70111. _this._buildPipeline();
  70112. return _this;
  70113. }
  70114. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  70115. get: function () {
  70116. return this._bloomEnabled;
  70117. },
  70118. set: function (enabled) {
  70119. if (this._bloomEnabled === enabled) {
  70120. return;
  70121. }
  70122. this._bloomEnabled = enabled;
  70123. this._buildPipeline();
  70124. },
  70125. enumerable: true,
  70126. configurable: true
  70127. });
  70128. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  70129. get: function () {
  70130. return this._depthOfFieldEnabled;
  70131. },
  70132. set: function (enabled) {
  70133. if (this._depthOfFieldEnabled === enabled) {
  70134. return;
  70135. }
  70136. this._depthOfFieldEnabled = enabled;
  70137. this._buildPipeline();
  70138. },
  70139. enumerable: true,
  70140. configurable: true
  70141. });
  70142. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  70143. get: function () {
  70144. return this._lensFlareEnabled;
  70145. },
  70146. set: function (enabled) {
  70147. if (this._lensFlareEnabled === enabled) {
  70148. return;
  70149. }
  70150. this._lensFlareEnabled = enabled;
  70151. this._buildPipeline();
  70152. },
  70153. enumerable: true,
  70154. configurable: true
  70155. });
  70156. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  70157. get: function () {
  70158. return this._hdrEnabled;
  70159. },
  70160. set: function (enabled) {
  70161. if (this._hdrEnabled === enabled) {
  70162. return;
  70163. }
  70164. this._hdrEnabled = enabled;
  70165. this._buildPipeline();
  70166. },
  70167. enumerable: true,
  70168. configurable: true
  70169. });
  70170. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  70171. get: function () {
  70172. return this._vlsEnabled;
  70173. },
  70174. set: function (enabled) {
  70175. if (this._vlsEnabled === enabled) {
  70176. return;
  70177. }
  70178. if (enabled) {
  70179. var geometry = this._scene.enableGeometryBufferRenderer();
  70180. if (!geometry) {
  70181. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  70182. return;
  70183. }
  70184. }
  70185. this._vlsEnabled = enabled;
  70186. this._buildPipeline();
  70187. },
  70188. enumerable: true,
  70189. configurable: true
  70190. });
  70191. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  70192. get: function () {
  70193. return this._motionBlurEnabled;
  70194. },
  70195. set: function (enabled) {
  70196. if (this._motionBlurEnabled === enabled) {
  70197. return;
  70198. }
  70199. this._motionBlurEnabled = enabled;
  70200. this._buildPipeline();
  70201. },
  70202. enumerable: true,
  70203. configurable: true
  70204. });
  70205. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  70206. get: function () {
  70207. return this._volumetricLightStepsCount;
  70208. },
  70209. set: function (count) {
  70210. if (this.volumetricLightPostProcess) {
  70211. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  70212. }
  70213. this._volumetricLightStepsCount = count;
  70214. },
  70215. enumerable: true,
  70216. configurable: true
  70217. });
  70218. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  70219. get: function () {
  70220. return this._motionBlurSamples;
  70221. },
  70222. set: function (samples) {
  70223. if (this.motionBlurPostProcess) {
  70224. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  70225. }
  70226. this._motionBlurSamples = samples;
  70227. },
  70228. enumerable: true,
  70229. configurable: true
  70230. });
  70231. StandardRenderingPipeline.prototype._buildPipeline = function () {
  70232. var _this = this;
  70233. var ratio = this._ratio;
  70234. var scene = this._scene;
  70235. this._disposePostProcesses();
  70236. this._reset();
  70237. // Create pass post-process
  70238. if (!this._basePostProcess) {
  70239. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  70240. this.originalPostProcess.onApply = function (effect) {
  70241. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  70242. };
  70243. }
  70244. else {
  70245. this.originalPostProcess = this._basePostProcess;
  70246. }
  70247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  70248. this._currentDepthOfFieldSource = this.originalPostProcess;
  70249. if (this._vlsEnabled) {
  70250. // Create volumetric light
  70251. this._createVolumetricLightPostProcess(scene, ratio);
  70252. // Create volumetric light final post-process
  70253. 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);
  70254. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  70255. }
  70256. if (this._bloomEnabled) {
  70257. // Create down sample X4 post-process
  70258. this._createDownSampleX4PostProcess(scene, ratio / 2);
  70259. // Create bright pass post-process
  70260. this._createBrightPassPostProcess(scene, ratio / 2);
  70261. // Create gaussian blur post-processes (down sampling blurs)
  70262. this._createBlurPostProcesses(scene, ratio / 4, 1);
  70263. // Create texture adder post-process
  70264. this._createTextureAdderPostProcess(scene, ratio);
  70265. // Create depth-of-field source post-process
  70266. 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);
  70267. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  70268. }
  70269. if (this._lensFlareEnabled) {
  70270. // Create lens flare post-process
  70271. this._createLensFlarePostProcess(scene, ratio);
  70272. // Create depth-of-field source post-process post lens-flare and disable it now
  70273. 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);
  70274. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  70275. }
  70276. if (this._hdrEnabled) {
  70277. // Create luminance
  70278. this._createLuminancePostProcesses(scene, this._floatTextureType);
  70279. // Create HDR
  70280. this._createHdrPostProcess(scene, ratio);
  70281. // Create depth-of-field source post-process post hdr and disable it now
  70282. 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);
  70283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  70284. }
  70285. if (this._depthOfFieldEnabled) {
  70286. // Create gaussian blur used by depth-of-field
  70287. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  70288. // Create depth-of-field post-process
  70289. this._createDepthOfFieldPostProcess(scene, ratio);
  70290. }
  70291. if (this._motionBlurEnabled) {
  70292. // Create motion blur post-process
  70293. this._createMotionBlurPostProcess(scene, ratio);
  70294. }
  70295. if (this._cameras !== null) {
  70296. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70297. }
  70298. };
  70299. // Down Sample X4 Post-Processs
  70300. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  70301. var _this = this;
  70302. var downSampleX4Offsets = new Array(32);
  70303. 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);
  70304. this.downSampleX4PostProcess.onApply = function (effect) {
  70305. var id = 0;
  70306. var width = _this.downSampleX4PostProcess.width;
  70307. var height = _this.downSampleX4PostProcess.height;
  70308. for (var i = -2; i < 2; i++) {
  70309. for (var j = -2; j < 2; j++) {
  70310. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  70311. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  70312. id += 2;
  70313. }
  70314. }
  70315. effect.setArray2("dsOffsets", downSampleX4Offsets);
  70316. };
  70317. // Add to pipeline
  70318. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  70319. };
  70320. // Brightpass Post-Process
  70321. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  70322. var _this = this;
  70323. var brightOffsets = new Array(8);
  70324. 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);
  70325. this.brightPassPostProcess.onApply = function (effect) {
  70326. var sU = (1.0 / _this.brightPassPostProcess.width);
  70327. var sV = (1.0 / _this.brightPassPostProcess.height);
  70328. brightOffsets[0] = -0.5 * sU;
  70329. brightOffsets[1] = 0.5 * sV;
  70330. brightOffsets[2] = 0.5 * sU;
  70331. brightOffsets[3] = 0.5 * sV;
  70332. brightOffsets[4] = -0.5 * sU;
  70333. brightOffsets[5] = -0.5 * sV;
  70334. brightOffsets[6] = 0.5 * sU;
  70335. brightOffsets[7] = -0.5 * sV;
  70336. effect.setArray2("dsOffsets", brightOffsets);
  70337. effect.setFloat("brightThreshold", _this.brightThreshold);
  70338. };
  70339. // Add to pipeline
  70340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  70341. };
  70342. // Create blur H&V post-processes
  70343. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  70344. var _this = this;
  70345. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  70346. var engine = scene.getEngine();
  70347. 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);
  70348. 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);
  70349. blurX.onActivateObservable.add(function () {
  70350. var dw = blurX.width / engine.getRenderWidth();
  70351. blurX.kernel = _this[blurWidthKey] * dw;
  70352. });
  70353. blurY.onActivateObservable.add(function () {
  70354. var dw = blurY.height / engine.getRenderHeight();
  70355. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  70356. });
  70357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  70358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  70359. this.blurHPostProcesses.push(blurX);
  70360. this.blurVPostProcesses.push(blurY);
  70361. };
  70362. // Create texture adder post-process
  70363. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  70364. var _this = this;
  70365. 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);
  70366. this.textureAdderPostProcess.onApply = function (effect) {
  70367. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  70368. effect.setTexture("lensSampler", _this.lensTexture);
  70369. effect.setFloat("exposure", _this.exposure);
  70370. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  70371. };
  70372. // Add to pipeline
  70373. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  70374. };
  70375. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  70376. var _this = this;
  70377. var geometryRenderer = scene.enableGeometryBufferRenderer();
  70378. geometryRenderer.enablePosition = true;
  70379. var geometry = geometryRenderer.getGBuffer();
  70380. // Base post-process
  70381. 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));
  70382. var depthValues = BABYLON.Vector2.Zero();
  70383. this.volumetricLightPostProcess.onApply = function (effect) {
  70384. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  70385. var generator = _this.sourceLight.getShadowGenerator();
  70386. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  70387. effect.setTexture("positionSampler", geometry.textures[2]);
  70388. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  70389. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  70390. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  70391. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  70392. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  70393. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  70394. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  70395. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  70396. effect.setVector2("depthValues", depthValues);
  70397. }
  70398. };
  70399. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  70400. // Smooth
  70401. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  70402. // Merge
  70403. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  70404. this.volumetricLightMergePostProces.onApply = function (effect) {
  70405. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  70406. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  70407. };
  70408. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  70409. };
  70410. // Create luminance
  70411. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  70412. var _this = this;
  70413. // Create luminance
  70414. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  70415. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  70416. var offsets = [];
  70417. this.luminancePostProcess.onApply = function (effect) {
  70418. var sU = (1.0 / _this.luminancePostProcess.width);
  70419. var sV = (1.0 / _this.luminancePostProcess.height);
  70420. offsets[0] = -0.5 * sU;
  70421. offsets[1] = 0.5 * sV;
  70422. offsets[2] = 0.5 * sU;
  70423. offsets[3] = 0.5 * sV;
  70424. offsets[4] = -0.5 * sU;
  70425. offsets[5] = -0.5 * sV;
  70426. offsets[6] = 0.5 * sU;
  70427. offsets[7] = -0.5 * sV;
  70428. effect.setArray2("lumOffsets", offsets);
  70429. };
  70430. // Add to pipeline
  70431. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  70432. // Create down sample luminance
  70433. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  70434. var size = Math.pow(3, i);
  70435. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  70436. if (i === 0) {
  70437. defines += "#define FINAL_DOWN_SAMPLER";
  70438. }
  70439. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  70440. this.luminanceDownSamplePostProcesses.push(postProcess);
  70441. }
  70442. // Create callbacks and add effects
  70443. var lastLuminance = this.luminancePostProcess;
  70444. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  70445. var downSampleOffsets = new Array(18);
  70446. pp.onApply = function (effect) {
  70447. if (!lastLuminance) {
  70448. return;
  70449. }
  70450. var id = 0;
  70451. for (var x = -1; x < 2; x++) {
  70452. for (var y = -1; y < 2; y++) {
  70453. downSampleOffsets[id] = x / lastLuminance.width;
  70454. downSampleOffsets[id + 1] = y / lastLuminance.height;
  70455. id += 2;
  70456. }
  70457. }
  70458. effect.setArray2("dsOffsets", downSampleOffsets);
  70459. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  70460. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  70461. lastLuminance = _this.luminancePostProcess;
  70462. }
  70463. else {
  70464. lastLuminance = pp;
  70465. }
  70466. };
  70467. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  70468. pp.onAfterRender = function (effect) {
  70469. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  70470. 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);
  70471. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  70472. };
  70473. }
  70474. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  70475. });
  70476. };
  70477. // Create HDR post-process
  70478. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  70479. var _this = this;
  70480. 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);
  70481. var outputLiminance = 1;
  70482. var time = 0;
  70483. var lastTime = 0;
  70484. this.hdrPostProcess.onApply = function (effect) {
  70485. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  70486. time += scene.getEngine().getDeltaTime();
  70487. if (outputLiminance < 0) {
  70488. outputLiminance = _this._hdrCurrentLuminance;
  70489. }
  70490. else {
  70491. var dt = (lastTime - time) / 1000.0;
  70492. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  70493. outputLiminance += _this.hdrDecreaseRate * dt;
  70494. }
  70495. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  70496. outputLiminance -= _this.hdrIncreaseRate * dt;
  70497. }
  70498. else {
  70499. outputLiminance = _this._hdrCurrentLuminance;
  70500. }
  70501. }
  70502. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  70503. effect.setFloat("averageLuminance", outputLiminance);
  70504. lastTime = time;
  70505. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  70506. };
  70507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  70508. };
  70509. // Create lens flare post-process
  70510. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  70511. var _this = this;
  70512. 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);
  70513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  70514. this._createBlurPostProcesses(scene, ratio / 4, 2);
  70515. 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);
  70516. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  70517. var resolution = new BABYLON.Vector2(0, 0);
  70518. // Lens flare
  70519. this.lensFlarePostProcess.onApply = function (effect) {
  70520. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  70521. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  70522. effect.setFloat("strength", _this.lensFlareStrength);
  70523. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  70524. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  70525. // Shift
  70526. resolution.x = _this.lensFlarePostProcess.width;
  70527. resolution.y = _this.lensFlarePostProcess.height;
  70528. effect.setVector2("resolution", resolution);
  70529. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  70530. };
  70531. // Compose
  70532. 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);
  70533. 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);
  70534. this.lensFlareComposePostProcess.onApply = function (effect) {
  70535. if (!_this._scene.activeCamera) {
  70536. return;
  70537. }
  70538. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  70539. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  70540. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  70541. // Lens start rotation matrix
  70542. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  70543. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  70544. 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));
  70545. camRot *= 4.0;
  70546. 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);
  70547. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  70548. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  70549. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  70550. };
  70551. };
  70552. // Create depth-of-field post-process
  70553. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  70554. var _this = this;
  70555. 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);
  70556. this.depthOfFieldPostProcess.onApply = function (effect) {
  70557. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  70558. effect.setTexture("depthSampler", _this._getDepthTexture());
  70559. effect.setFloat("distance", _this.depthOfFieldDistance);
  70560. };
  70561. // Add to pipeline
  70562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  70563. };
  70564. // Create motion blur post-process
  70565. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  70566. var _this = this;
  70567. 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);
  70568. var motionScale = 0;
  70569. var prevViewProjection = BABYLON.Matrix.Identity();
  70570. var invViewProjection = BABYLON.Matrix.Identity();
  70571. var viewProjection = BABYLON.Matrix.Identity();
  70572. var screenSize = BABYLON.Vector2.Zero();
  70573. this.motionBlurPostProcess.onApply = function (effect) {
  70574. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  70575. viewProjection.invertToRef(invViewProjection);
  70576. effect.setMatrix("inverseViewProjection", invViewProjection);
  70577. effect.setMatrix("prevViewProjection", prevViewProjection);
  70578. prevViewProjection = viewProjection;
  70579. screenSize.x = _this.motionBlurPostProcess.width;
  70580. screenSize.y = _this.motionBlurPostProcess.height;
  70581. effect.setVector2("screenSize", screenSize);
  70582. motionScale = scene.getEngine().getFps() / 60.0;
  70583. effect.setFloat("motionScale", motionScale);
  70584. effect.setFloat("motionStrength", _this.motionStrength);
  70585. effect.setTexture("depthSampler", _this._getDepthTexture());
  70586. };
  70587. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  70588. };
  70589. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  70590. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  70591. var renderer = this._scene.enableGeometryBufferRenderer();
  70592. return renderer.getGBuffer().textures[0];
  70593. }
  70594. return this._scene.enableDepthRenderer().getDepthMap();
  70595. };
  70596. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  70597. for (var i = 0; i < this._cameras.length; i++) {
  70598. var camera = this._cameras[i];
  70599. if (this.originalPostProcess) {
  70600. this.originalPostProcess.dispose(camera);
  70601. }
  70602. if (this.downSampleX4PostProcess) {
  70603. this.downSampleX4PostProcess.dispose(camera);
  70604. }
  70605. if (this.brightPassPostProcess) {
  70606. this.brightPassPostProcess.dispose(camera);
  70607. }
  70608. if (this.textureAdderPostProcess) {
  70609. this.textureAdderPostProcess.dispose(camera);
  70610. }
  70611. if (this.textureAdderFinalPostProcess) {
  70612. this.textureAdderFinalPostProcess.dispose(camera);
  70613. }
  70614. if (this.volumetricLightPostProcess) {
  70615. this.volumetricLightPostProcess.dispose(camera);
  70616. }
  70617. if (this.volumetricLightSmoothXPostProcess) {
  70618. this.volumetricLightSmoothXPostProcess.dispose(camera);
  70619. }
  70620. if (this.volumetricLightSmoothYPostProcess) {
  70621. this.volumetricLightSmoothYPostProcess.dispose(camera);
  70622. }
  70623. if (this.volumetricLightMergePostProces) {
  70624. this.volumetricLightMergePostProces.dispose(camera);
  70625. }
  70626. if (this.volumetricLightFinalPostProcess) {
  70627. this.volumetricLightFinalPostProcess.dispose(camera);
  70628. }
  70629. if (this.lensFlarePostProcess) {
  70630. this.lensFlarePostProcess.dispose(camera);
  70631. }
  70632. if (this.lensFlareComposePostProcess) {
  70633. this.lensFlareComposePostProcess.dispose(camera);
  70634. }
  70635. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  70636. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  70637. }
  70638. if (this.luminancePostProcess) {
  70639. this.luminancePostProcess.dispose(camera);
  70640. }
  70641. if (this.hdrPostProcess) {
  70642. this.hdrPostProcess.dispose(camera);
  70643. }
  70644. if (this.hdrFinalPostProcess) {
  70645. this.hdrFinalPostProcess.dispose(camera);
  70646. }
  70647. if (this.depthOfFieldPostProcess) {
  70648. this.depthOfFieldPostProcess.dispose(camera);
  70649. }
  70650. if (this.motionBlurPostProcess) {
  70651. this.motionBlurPostProcess.dispose(camera);
  70652. }
  70653. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  70654. this.blurHPostProcesses[j].dispose(camera);
  70655. }
  70656. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  70657. this.blurVPostProcesses[j].dispose(camera);
  70658. }
  70659. }
  70660. this.originalPostProcess = null;
  70661. this.downSampleX4PostProcess = null;
  70662. this.brightPassPostProcess = null;
  70663. this.textureAdderPostProcess = null;
  70664. this.textureAdderFinalPostProcess = null;
  70665. this.volumetricLightPostProcess = null;
  70666. this.volumetricLightSmoothXPostProcess = null;
  70667. this.volumetricLightSmoothYPostProcess = null;
  70668. this.volumetricLightMergePostProces = null;
  70669. this.volumetricLightFinalPostProcess = null;
  70670. this.lensFlarePostProcess = null;
  70671. this.lensFlareComposePostProcess = null;
  70672. this.luminancePostProcess = null;
  70673. this.hdrPostProcess = null;
  70674. this.hdrFinalPostProcess = null;
  70675. this.depthOfFieldPostProcess = null;
  70676. this.motionBlurPostProcess = null;
  70677. this.luminanceDownSamplePostProcesses = [];
  70678. this.blurHPostProcesses = [];
  70679. this.blurVPostProcesses = [];
  70680. };
  70681. // Dispose
  70682. StandardRenderingPipeline.prototype.dispose = function () {
  70683. this._disposePostProcesses();
  70684. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70685. _super.prototype.dispose.call(this);
  70686. };
  70687. // Serialize rendering pipeline
  70688. StandardRenderingPipeline.prototype.serialize = function () {
  70689. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70690. serializationObject.customType = "StandardRenderingPipeline";
  70691. return serializationObject;
  70692. };
  70693. /**
  70694. * Static members
  70695. */
  70696. // Parse serialized pipeline
  70697. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70698. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  70699. };
  70700. // Luminance steps
  70701. StandardRenderingPipeline.LuminanceSteps = 6;
  70702. __decorate([
  70703. BABYLON.serialize()
  70704. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  70705. __decorate([
  70706. BABYLON.serialize()
  70707. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  70708. __decorate([
  70709. BABYLON.serialize()
  70710. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  70711. __decorate([
  70712. BABYLON.serialize()
  70713. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  70714. __decorate([
  70715. BABYLON.serializeAsTexture("lensTexture")
  70716. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  70717. __decorate([
  70718. BABYLON.serialize()
  70719. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  70720. __decorate([
  70721. BABYLON.serialize()
  70722. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  70723. __decorate([
  70724. BABYLON.serialize()
  70725. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  70726. __decorate([
  70727. BABYLON.serialize()
  70728. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  70729. __decorate([
  70730. BABYLON.serialize()
  70731. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  70732. __decorate([
  70733. BABYLON.serialize()
  70734. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  70735. __decorate([
  70736. BABYLON.serializeAsTexture("lensColorTexture")
  70737. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  70738. __decorate([
  70739. BABYLON.serialize()
  70740. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  70741. __decorate([
  70742. BABYLON.serialize()
  70743. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  70744. __decorate([
  70745. BABYLON.serialize()
  70746. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  70747. __decorate([
  70748. BABYLON.serialize()
  70749. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  70750. __decorate([
  70751. BABYLON.serializeAsTexture("lensStarTexture")
  70752. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  70753. __decorate([
  70754. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  70755. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  70756. __decorate([
  70757. BABYLON.serialize()
  70758. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  70759. __decorate([
  70760. BABYLON.serialize()
  70761. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  70762. __decorate([
  70763. BABYLON.serialize()
  70764. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  70765. __decorate([
  70766. BABYLON.serialize()
  70767. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  70768. __decorate([
  70769. BABYLON.serialize()
  70770. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  70771. __decorate([
  70772. BABYLON.serialize()
  70773. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  70774. __decorate([
  70775. BABYLON.serialize()
  70776. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  70777. __decorate([
  70778. BABYLON.serialize()
  70779. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  70780. __decorate([
  70781. BABYLON.serialize()
  70782. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  70783. __decorate([
  70784. BABYLON.serialize()
  70785. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  70786. __decorate([
  70787. BABYLON.serialize()
  70788. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  70789. __decorate([
  70790. BABYLON.serialize()
  70791. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  70792. return StandardRenderingPipeline;
  70793. }(BABYLON.PostProcessRenderPipeline));
  70794. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  70795. })(BABYLON || (BABYLON = {}));
  70796. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  70797. "use strict";
  70798. var BABYLON;
  70799. (function (BABYLON) {
  70800. var FxaaPostProcess = /** @class */ (function (_super) {
  70801. __extends(FxaaPostProcess, _super);
  70802. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70803. if (camera === void 0) { camera = null; }
  70804. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70805. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  70806. _this.onApplyObservable.add(function (effect) {
  70807. var texelSize = _this.texelSize;
  70808. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  70809. });
  70810. return _this;
  70811. }
  70812. return FxaaPostProcess;
  70813. }(BABYLON.PostProcess));
  70814. BABYLON.FxaaPostProcess = FxaaPostProcess;
  70815. })(BABYLON || (BABYLON = {}));
  70816. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  70817. "use strict";
  70818. var BABYLON;
  70819. (function (BABYLON) {
  70820. /**
  70821. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  70822. */
  70823. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  70824. __extends(ChromaticAberrationPostProcess, _super);
  70825. /**
  70826. * Creates a new instance ChromaticAberrationPostProcess
  70827. * @param name The name of the effect.
  70828. * @param screenWidth The width of the screen to apply the effect on.
  70829. * @param screenHeight The height of the screen to apply the effect on.
  70830. * @param options The required width/height ratio to downsize to before computing the render pass.
  70831. * @param camera The camera to apply the render pass to.
  70832. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70833. * @param engine The engine which the post process will be applied. (default: current engine)
  70834. * @param reusable If the post process can be reused on the same frame. (default: false)
  70835. * @param textureType Type of textures used when performing the post process. (default: 0)
  70836. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70837. */
  70838. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70839. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70840. if (blockCompilation === void 0) { blockCompilation = false; }
  70841. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70842. /**
  70843. * The amount of seperation of rgb channels (default: 30)
  70844. */
  70845. _this.aberrationAmount = 30;
  70846. /**
  70847. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  70848. */
  70849. _this.radialIntensity = 0;
  70850. /**
  70851. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  70852. */
  70853. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  70854. /**
  70855. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  70856. */
  70857. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  70858. _this.onApplyObservable.add(function (effect) {
  70859. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  70860. effect.setFloat('screen_width', screenWidth);
  70861. effect.setFloat('screen_height', screenHeight);
  70862. effect.setFloat('radialIntensity', _this.radialIntensity);
  70863. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  70864. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  70865. });
  70866. return _this;
  70867. }
  70868. return ChromaticAberrationPostProcess;
  70869. }(BABYLON.PostProcess));
  70870. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  70871. })(BABYLON || (BABYLON = {}));
  70872. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  70873. "use strict";
  70874. var BABYLON;
  70875. (function (BABYLON) {
  70876. /**
  70877. * The GrainPostProcess adds noise to the image at mid luminance levels
  70878. */
  70879. var GrainPostProcess = /** @class */ (function (_super) {
  70880. __extends(GrainPostProcess, _super);
  70881. /**
  70882. * Creates a new instance of @see GrainPostProcess
  70883. * @param name The name of the effect.
  70884. * @param options The required width/height ratio to downsize to before computing the render pass.
  70885. * @param camera The camera to apply the render pass to.
  70886. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70887. * @param engine The engine which the post process will be applied. (default: current engine)
  70888. * @param reusable If the post process can be reused on the same frame. (default: false)
  70889. * @param textureType Type of textures used when performing the post process. (default: 0)
  70890. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70891. */
  70892. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70893. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70894. if (blockCompilation === void 0) { blockCompilation = false; }
  70895. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70896. /**
  70897. * The intensity of the grain added (default: 30)
  70898. */
  70899. _this.intensity = 30;
  70900. /**
  70901. * If the grain should be randomized on every frame
  70902. */
  70903. _this.animated = false;
  70904. _this.onApplyObservable.add(function (effect) {
  70905. effect.setFloat('intensity', _this.intensity);
  70906. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  70907. });
  70908. return _this;
  70909. }
  70910. return GrainPostProcess;
  70911. }(BABYLON.PostProcess));
  70912. BABYLON.GrainPostProcess = GrainPostProcess;
  70913. })(BABYLON || (BABYLON = {}));
  70914. //# sourceMappingURL=babylon.grainPostProcess.js.map
  70915. "use strict";
  70916. var BABYLON;
  70917. (function (BABYLON) {
  70918. /**
  70919. * The SharpenPostProcess applies a sharpen kernel to every pixel
  70920. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70921. */
  70922. var SharpenPostProcess = /** @class */ (function (_super) {
  70923. __extends(SharpenPostProcess, _super);
  70924. /**
  70925. * Creates a new instance ConvolutionPostProcess
  70926. * @param name The name of the effect.
  70927. * @param options The required width/height ratio to downsize to before computing the render pass.
  70928. * @param camera The camera to apply the render pass to.
  70929. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70930. * @param engine The engine which the post process will be applied. (default: current engine)
  70931. * @param reusable If the post process can be reused on the same frame. (default: false)
  70932. * @param textureType Type of textures used when performing the post process. (default: 0)
  70933. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70934. */
  70935. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70936. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70937. if (blockCompilation === void 0) { blockCompilation = false; }
  70938. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70939. /**
  70940. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  70941. */
  70942. _this.colorAmount = 1.0;
  70943. /**
  70944. * How much sharpness should be applied (default: 0.3)
  70945. */
  70946. _this.edgeAmount = 0.3;
  70947. _this.onApply = function (effect) {
  70948. effect.setFloat2("screenSize", _this.width, _this.height);
  70949. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  70950. };
  70951. return _this;
  70952. }
  70953. return SharpenPostProcess;
  70954. }(BABYLON.PostProcess));
  70955. BABYLON.SharpenPostProcess = SharpenPostProcess;
  70956. })(BABYLON || (BABYLON = {}));
  70957. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  70958. "use strict";
  70959. var BABYLON;
  70960. (function (BABYLON) {
  70961. /**
  70962. * The Blur Post Process which blurs an image based on a kernel and direction.
  70963. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70964. */
  70965. var BlurPostProcess = /** @class */ (function (_super) {
  70966. __extends(BlurPostProcess, _super);
  70967. /**
  70968. * Creates a new instance BlurPostProcess
  70969. * @param name The name of the effect.
  70970. * @param direction The direction in which to blur the image.
  70971. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  70972. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70973. * @param camera The camera to apply the render pass to.
  70974. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70975. * @param engine The engine which the post process will be applied. (default: current engine)
  70976. * @param reusable If the post process can be reused on the same frame. (default: false)
  70977. * @param textureType Type of textures used when performing the post process. (default: 0)
  70978. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70979. */
  70980. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  70981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70982. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70983. if (defines === void 0) { defines = ""; }
  70984. if (blockCompilation === void 0) { blockCompilation = false; }
  70985. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  70986. _this.direction = direction;
  70987. _this.blockCompilation = blockCompilation;
  70988. _this._packedFloat = false;
  70989. _this._staticDefines = "";
  70990. _this._staticDefines = defines;
  70991. _this.onApplyObservable.add(function (effect) {
  70992. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70993. });
  70994. _this.kernel = kernel;
  70995. return _this;
  70996. }
  70997. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70998. /**
  70999. * Gets the length in pixels of the blur sample region
  71000. */
  71001. get: function () {
  71002. return this._idealKernel;
  71003. },
  71004. /**
  71005. * Sets the length in pixels of the blur sample region
  71006. */
  71007. set: function (v) {
  71008. if (this._idealKernel === v) {
  71009. return;
  71010. }
  71011. v = Math.max(v, 1);
  71012. this._idealKernel = v;
  71013. this._kernel = this._nearestBestKernel(v);
  71014. if (!this.blockCompilation) {
  71015. this._updateParameters();
  71016. }
  71017. },
  71018. enumerable: true,
  71019. configurable: true
  71020. });
  71021. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  71022. /**
  71023. * Gets wether or not the blur is unpacking/repacking floats
  71024. */
  71025. get: function () {
  71026. return this._packedFloat;
  71027. },
  71028. /**
  71029. * Sets wether or not the blur needs to unpack/repack floats
  71030. */
  71031. set: function (v) {
  71032. if (this._packedFloat === v) {
  71033. return;
  71034. }
  71035. this._packedFloat = v;
  71036. if (!this.blockCompilation) {
  71037. this._updateParameters();
  71038. }
  71039. },
  71040. enumerable: true,
  71041. configurable: true
  71042. });
  71043. /**
  71044. * Updates the effect with the current post process compile time values and recompiles the shader.
  71045. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71046. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71047. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71048. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  71049. * @param onCompiled Called when the shader has been compiled.
  71050. * @param onError Called if there is an error when compiling a shader.
  71051. */
  71052. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71053. if (defines === void 0) { defines = null; }
  71054. if (uniforms === void 0) { uniforms = null; }
  71055. if (samplers === void 0) { samplers = null; }
  71056. this._updateParameters(onCompiled, onError);
  71057. };
  71058. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  71059. // Generate sampling offsets and weights
  71060. var N = this._kernel;
  71061. var centerIndex = (N - 1) / 2;
  71062. // Generate Gaussian sampling weights over kernel
  71063. var offsets = [];
  71064. var weights = [];
  71065. var totalWeight = 0;
  71066. for (var i = 0; i < N; i++) {
  71067. var u = i / (N - 1);
  71068. var w = this._gaussianWeight(u * 2.0 - 1);
  71069. offsets[i] = (i - centerIndex);
  71070. weights[i] = w;
  71071. totalWeight += w;
  71072. }
  71073. // Normalize weights
  71074. for (var i = 0; i < weights.length; i++) {
  71075. weights[i] /= totalWeight;
  71076. }
  71077. // Optimize: combine samples to take advantage of hardware linear sampling
  71078. // Walk from left to center, combining pairs (symmetrically)
  71079. var linearSamplingWeights = [];
  71080. var linearSamplingOffsets = [];
  71081. var linearSamplingMap = [];
  71082. for (var i = 0; i <= centerIndex; i += 2) {
  71083. var j = Math.min(i + 1, Math.floor(centerIndex));
  71084. var singleCenterSample = i === j;
  71085. if (singleCenterSample) {
  71086. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  71087. }
  71088. else {
  71089. var sharedCell = j === centerIndex;
  71090. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  71091. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  71092. if (offsetLinear === 0) {
  71093. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  71094. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  71095. }
  71096. else {
  71097. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  71098. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  71099. }
  71100. }
  71101. }
  71102. for (var i = 0; i < linearSamplingMap.length; i++) {
  71103. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  71104. linearSamplingWeights[i] = linearSamplingMap[i].w;
  71105. }
  71106. // Replace with optimized
  71107. offsets = linearSamplingOffsets;
  71108. weights = linearSamplingWeights;
  71109. // Generate shaders
  71110. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  71111. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  71112. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  71113. var defines = "";
  71114. defines += this._staticDefines;
  71115. for (var i = 0; i < varyingCount; i++) {
  71116. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  71117. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  71118. }
  71119. var depCount = 0;
  71120. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  71121. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  71122. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  71123. depCount++;
  71124. }
  71125. if (this.packedFloat) {
  71126. defines += "#define PACKEDFLOAT 1";
  71127. }
  71128. this.blockCompilation = false;
  71129. _super.prototype.updateEffect.call(this, defines, null, null, {
  71130. varyingCount: varyingCount,
  71131. depCount: depCount
  71132. }, onCompiled, onError);
  71133. };
  71134. /**
  71135. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  71136. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  71137. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  71138. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  71139. * The gaps between physical kernels are compensated for in the weighting of the samples
  71140. * @param idealKernel Ideal blur kernel.
  71141. * @return Nearest best kernel.
  71142. */
  71143. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  71144. var v = Math.round(idealKernel);
  71145. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  71146. var k = _a[_i];
  71147. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  71148. return Math.max(k, 3);
  71149. }
  71150. }
  71151. return Math.max(v, 3);
  71152. };
  71153. /**
  71154. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  71155. * @param x The point on the Gaussian distribution to sample.
  71156. * @return the value of the Gaussian function at x.
  71157. */
  71158. BlurPostProcess.prototype._gaussianWeight = function (x) {
  71159. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  71160. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  71161. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  71162. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  71163. // truncated at around 1.3% of peak strength.
  71164. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  71165. var sigma = (1 / 3);
  71166. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  71167. var exponent = -((x * x) / (2.0 * sigma * sigma));
  71168. var weight = (1.0 / denominator) * Math.exp(exponent);
  71169. return weight;
  71170. };
  71171. /**
  71172. * Generates a string that can be used as a floating point number in GLSL.
  71173. * @param x Value to print.
  71174. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  71175. * @return GLSL float string.
  71176. */
  71177. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  71178. if (decimalFigures === void 0) { decimalFigures = 8; }
  71179. return x.toFixed(decimalFigures).replace(/0+$/, '');
  71180. };
  71181. return BlurPostProcess;
  71182. }(BABYLON.PostProcess));
  71183. BABYLON.BlurPostProcess = BlurPostProcess;
  71184. })(BABYLON || (BABYLON = {}));
  71185. //# sourceMappingURL=babylon.blurPostProcess.js.map
  71186. "use strict";
  71187. var BABYLON;
  71188. (function (BABYLON) {
  71189. /**
  71190. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  71191. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  71192. * based on samples that have a large difference in distance than the center pixel.
  71193. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  71194. */
  71195. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  71196. __extends(DepthOfFieldBlurPostProcess, _super);
  71197. /**
  71198. * Creates a new instance CircleOfConfusionPostProcess
  71199. * @param name The name of the effect.
  71200. * @param scene The scene the effect belongs to.
  71201. * @param direction The direction the blur should be applied.
  71202. * @param kernel The size of the kernel used to blur.
  71203. * @param options The required width/height ratio to downsize to before computing the render pass.
  71204. * @param camera The camera to apply the render pass to.
  71205. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  71206. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  71207. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71208. * @param engine The engine which the post process will be applied. (default: current engine)
  71209. * @param reusable If the post process can be reused on the same frame. (default: false)
  71210. * @param textureType Type of textures used when performing the post process. (default: 0)
  71211. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  71212. */
  71213. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  71214. if (imageToBlur === void 0) { imageToBlur = null; }
  71215. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71216. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71217. if (blockCompilation === void 0) { blockCompilation = false; }
  71218. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  71219. _this.direction = direction;
  71220. _this.onApplyObservable.add(function (effect) {
  71221. if (imageToBlur != null) {
  71222. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  71223. }
  71224. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  71225. if (scene.activeCamera) {
  71226. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  71227. }
  71228. });
  71229. return _this;
  71230. }
  71231. return DepthOfFieldBlurPostProcess;
  71232. }(BABYLON.BlurPostProcess));
  71233. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  71234. })(BABYLON || (BABYLON = {}));
  71235. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  71236. "use strict";
  71237. var BABYLON;
  71238. (function (BABYLON) {
  71239. /**
  71240. * Options to be set when merging outputs from the default pipeline.
  71241. */
  71242. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  71243. function DepthOfFieldMergePostProcessOptions() {
  71244. }
  71245. return DepthOfFieldMergePostProcessOptions;
  71246. }());
  71247. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  71248. /**
  71249. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  71250. */
  71251. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  71252. __extends(DepthOfFieldMergePostProcess, _super);
  71253. /**
  71254. * Creates a new instance of DepthOfFieldMergePostProcess
  71255. * @param name The name of the effect.
  71256. * @param originalFromInput Post process which's input will be used for the merge.
  71257. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  71258. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  71259. * @param options The required width/height ratio to downsize to before computing the render pass.
  71260. * @param camera The camera to apply the render pass to.
  71261. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71262. * @param engine The engine which the post process will be applied. (default: current engine)
  71263. * @param reusable If the post process can be reused on the same frame. (default: false)
  71264. * @param textureType Type of textures used when performing the post process. (default: 0)
  71265. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  71266. */
  71267. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71268. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71269. if (blockCompilation === void 0) { blockCompilation = false; }
  71270. var _this = _super.call(this, name, "depthOfFieldMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  71271. _this.blurSteps = blurSteps;
  71272. _this.onApplyObservable.add(function (effect) {
  71273. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  71274. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  71275. blurSteps.forEach(function (step, index) {
  71276. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  71277. });
  71278. });
  71279. if (!blockCompilation) {
  71280. _this.updateEffect();
  71281. }
  71282. return _this;
  71283. }
  71284. /**
  71285. * Updates the effect with the current post process compile time values and recompiles the shader.
  71286. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71287. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71288. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71289. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  71290. * @param onCompiled Called when the shader has been compiled.
  71291. * @param onError Called if there is an error when compiling a shader.
  71292. */
  71293. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71294. if (defines === void 0) { defines = null; }
  71295. if (uniforms === void 0) { uniforms = null; }
  71296. if (samplers === void 0) { samplers = null; }
  71297. if (!defines) {
  71298. defines = "";
  71299. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  71300. }
  71301. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  71302. };
  71303. return DepthOfFieldMergePostProcess;
  71304. }(BABYLON.PostProcess));
  71305. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  71306. })(BABYLON || (BABYLON = {}));
  71307. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  71308. "use strict";
  71309. var BABYLON;
  71310. (function (BABYLON) {
  71311. /**
  71312. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  71313. */
  71314. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  71315. __extends(CircleOfConfusionPostProcess, _super);
  71316. /**
  71317. * Creates a new instance CircleOfConfusionPostProcess
  71318. * @param name The name of the effect.
  71319. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  71320. * @param options The required width/height ratio to downsize to before computing the render pass.
  71321. * @param camera The camera to apply the render pass to.
  71322. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71323. * @param engine The engine which the post process will be applied. (default: current engine)
  71324. * @param reusable If the post process can be reused on the same frame. (default: false)
  71325. * @param textureType Type of textures used when performing the post process. (default: 0)
  71326. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  71327. */
  71328. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71329. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71330. if (blockCompilation === void 0) { blockCompilation = false; }
  71331. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  71332. /**
  71333. * 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.
  71334. */
  71335. _this.lensSize = 50;
  71336. /**
  71337. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  71338. */
  71339. _this.fStop = 1.4;
  71340. /**
  71341. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  71342. */
  71343. _this.focusDistance = 2000;
  71344. /**
  71345. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  71346. */
  71347. _this.focalLength = 50;
  71348. _this._depthTexture = null;
  71349. _this._depthTexture = depthTexture;
  71350. _this.onApplyObservable.add(function (effect) {
  71351. if (!_this._depthTexture) {
  71352. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  71353. return;
  71354. }
  71355. effect.setTexture("depthSampler", _this._depthTexture);
  71356. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  71357. var aperture = _this.lensSize / _this.fStop;
  71358. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  71359. effect.setFloat('focusDistance', _this.focusDistance);
  71360. effect.setFloat('cocPrecalculation', cocPrecalculation);
  71361. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  71362. });
  71363. return _this;
  71364. }
  71365. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  71366. /**
  71367. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  71368. */
  71369. set: function (value) {
  71370. this._depthTexture = value;
  71371. },
  71372. enumerable: true,
  71373. configurable: true
  71374. });
  71375. return CircleOfConfusionPostProcess;
  71376. }(BABYLON.PostProcess));
  71377. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  71378. })(BABYLON || (BABYLON = {}));
  71379. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  71380. "use strict";
  71381. var BABYLON;
  71382. (function (BABYLON) {
  71383. /**
  71384. * Specifies the level of max blur that should be applied when using the depth of field effect
  71385. */
  71386. var DepthOfFieldEffectBlurLevel;
  71387. (function (DepthOfFieldEffectBlurLevel) {
  71388. /**
  71389. * Subtle blur
  71390. */
  71391. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  71392. /**
  71393. * Medium blur
  71394. */
  71395. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  71396. /**
  71397. * Large blur
  71398. */
  71399. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  71400. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  71401. ;
  71402. /**
  71403. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  71404. */
  71405. var DepthOfFieldEffect = /** @class */ (function (_super) {
  71406. __extends(DepthOfFieldEffect, _super);
  71407. /**
  71408. * Creates a new instance DepthOfFieldEffect
  71409. * @param scene The scene the effect belongs to.
  71410. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  71411. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  71412. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  71413. */
  71414. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  71415. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  71416. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  71417. if (blockCompilation === void 0) { blockCompilation = false; }
  71418. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  71419. return _this._effects;
  71420. }, true) || this;
  71421. /**
  71422. * Internal post processes in depth of field effect
  71423. */
  71424. _this._effects = [];
  71425. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  71426. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71427. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  71428. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  71429. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  71430. _this._depthOfFieldBlurY = [];
  71431. _this._depthOfFieldBlurX = [];
  71432. var blurCount = 1;
  71433. var kernelSize = 15;
  71434. switch (blurLevel) {
  71435. case DepthOfFieldEffectBlurLevel.High: {
  71436. blurCount = 3;
  71437. kernelSize = 51;
  71438. break;
  71439. }
  71440. case DepthOfFieldEffectBlurLevel.Medium: {
  71441. blurCount = 2;
  71442. kernelSize = 31;
  71443. break;
  71444. }
  71445. default: {
  71446. kernelSize = 15;
  71447. blurCount = 1;
  71448. break;
  71449. }
  71450. }
  71451. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  71452. for (var i = 0; i < blurCount; i++) {
  71453. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71454. blurY.autoClear = false;
  71455. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71456. blurX.autoClear = false;
  71457. _this._depthOfFieldBlurY.push(blurY);
  71458. _this._depthOfFieldBlurX.push(blurX);
  71459. }
  71460. // Set all post processes on the effect.
  71461. _this._effects = [_this._circleOfConfusion];
  71462. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  71463. _this._effects.push(_this._depthOfFieldBlurY[i]);
  71464. _this._effects.push(_this._depthOfFieldBlurX[i]);
  71465. }
  71466. // Merge blurred images with original image based on circleOfConfusion
  71467. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71468. _this._dofMerge.autoClear = false;
  71469. _this._effects.push(_this._dofMerge);
  71470. return _this;
  71471. }
  71472. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  71473. get: function () {
  71474. return this._circleOfConfusion.focalLength;
  71475. },
  71476. /**
  71477. * The focal the length of the camera used in the effect
  71478. */
  71479. set: function (value) {
  71480. this._circleOfConfusion.focalLength = value;
  71481. },
  71482. enumerable: true,
  71483. configurable: true
  71484. });
  71485. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  71486. get: function () {
  71487. return this._circleOfConfusion.fStop;
  71488. },
  71489. /**
  71490. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  71491. */
  71492. set: function (value) {
  71493. this._circleOfConfusion.fStop = value;
  71494. },
  71495. enumerable: true,
  71496. configurable: true
  71497. });
  71498. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  71499. get: function () {
  71500. return this._circleOfConfusion.focusDistance;
  71501. },
  71502. /**
  71503. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  71504. */
  71505. set: function (value) {
  71506. this._circleOfConfusion.focusDistance = value;
  71507. },
  71508. enumerable: true,
  71509. configurable: true
  71510. });
  71511. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  71512. get: function () {
  71513. return this._circleOfConfusion.lensSize;
  71514. },
  71515. /**
  71516. * 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.
  71517. */
  71518. set: function (value) {
  71519. this._circleOfConfusion.lensSize = value;
  71520. },
  71521. enumerable: true,
  71522. configurable: true
  71523. });
  71524. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  71525. /**
  71526. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  71527. */
  71528. set: function (value) {
  71529. this._circleOfConfusion.depthTexture = value;
  71530. },
  71531. enumerable: true,
  71532. configurable: true
  71533. });
  71534. /**
  71535. * Disposes each of the internal effects for a given camera.
  71536. * @param camera The camera to dispose the effect on.
  71537. */
  71538. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  71539. for (var effect in this._effects) {
  71540. this._effects[effect].dispose(camera);
  71541. }
  71542. };
  71543. /**
  71544. * Internal
  71545. */
  71546. DepthOfFieldEffect.prototype._updateEffects = function () {
  71547. for (var effect in this._effects) {
  71548. this._effects[effect].updateEffect();
  71549. }
  71550. };
  71551. /**
  71552. * Internal
  71553. * @returns if all the contained post processes are ready.
  71554. */
  71555. DepthOfFieldEffect.prototype._isReady = function () {
  71556. for (var effect in this._effects) {
  71557. if (!this._effects[effect].isReady()) {
  71558. return false;
  71559. }
  71560. }
  71561. return true;
  71562. };
  71563. return DepthOfFieldEffect;
  71564. }(BABYLON.PostProcessRenderEffect));
  71565. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  71566. })(BABYLON || (BABYLON = {}));
  71567. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  71568. "use strict";
  71569. var BABYLON;
  71570. (function (BABYLON) {
  71571. /**
  71572. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  71573. */
  71574. var BloomMergePostProcess = /** @class */ (function (_super) {
  71575. __extends(BloomMergePostProcess, _super);
  71576. /**
  71577. * Creates a new instance of @see BloomMergePostProcess
  71578. * @param name The name of the effect.
  71579. * @param originalFromInput Post process which's input will be used for the merge.
  71580. * @param blurred Blurred highlights post process which's output will be used.
  71581. * @param weight Weight of the bloom to be added to the original input.
  71582. * @param options The required width/height ratio to downsize to before computing the render pass.
  71583. * @param camera The camera to apply the render pass to.
  71584. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71585. * @param engine The engine which the post process will be applied. (default: current engine)
  71586. * @param reusable If the post process can be reused on the same frame. (default: false)
  71587. * @param textureType Type of textures used when performing the post process. (default: 0)
  71588. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  71589. */
  71590. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71591. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71592. if (blockCompilation === void 0) { blockCompilation = false; }
  71593. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  71594. _this.weight = weight;
  71595. _this.onApplyObservable.add(function (effect) {
  71596. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  71597. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  71598. effect.setFloat("bloomWeight", _this.weight);
  71599. });
  71600. if (!blockCompilation) {
  71601. _this.updateEffect();
  71602. }
  71603. return _this;
  71604. }
  71605. return BloomMergePostProcess;
  71606. }(BABYLON.PostProcess));
  71607. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  71608. })(BABYLON || (BABYLON = {}));
  71609. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  71610. "use strict";
  71611. var BABYLON;
  71612. (function (BABYLON) {
  71613. /**
  71614. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  71615. */
  71616. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  71617. __extends(ExtractHighlightsPostProcess, _super);
  71618. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71619. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71620. if (blockCompilation === void 0) { blockCompilation = false; }
  71621. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  71622. /**
  71623. * The luminance threshold, pixels below this value will be set to black.
  71624. */
  71625. _this.threshold = 0.9;
  71626. /**
  71627. * Internal
  71628. */
  71629. _this._exposure = 1;
  71630. /**
  71631. * Post process which has the input texture to be used when performing highlight extraction
  71632. */
  71633. _this._inputPostProcess = null;
  71634. _this.onApplyObservable.add(function (effect) {
  71635. if (_this._inputPostProcess) {
  71636. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  71637. }
  71638. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  71639. effect.setFloat('exposure', _this._exposure);
  71640. });
  71641. return _this;
  71642. }
  71643. return ExtractHighlightsPostProcess;
  71644. }(BABYLON.PostProcess));
  71645. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  71646. })(BABYLON || (BABYLON = {}));
  71647. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  71648. "use strict";
  71649. var BABYLON;
  71650. (function (BABYLON) {
  71651. /**
  71652. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  71653. */
  71654. var BloomEffect = /** @class */ (function (_super) {
  71655. __extends(BloomEffect, _super);
  71656. /**
  71657. * Creates a new instance of @see BloomEffect
  71658. * @param scene The scene the effect belongs to.
  71659. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  71660. * @param bloomKernel The size of the kernel to be used when applying the blur.
  71661. * @param bloomWeight The the strength of bloom.
  71662. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  71663. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  71664. */
  71665. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  71666. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  71667. if (blockCompilation === void 0) { blockCompilation = false; }
  71668. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  71669. return _this._effects;
  71670. }, true) || this;
  71671. _this.bloomScale = bloomScale;
  71672. /**
  71673. * Internal
  71674. */
  71675. _this._effects = [];
  71676. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71677. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  71678. _this._blurX.alwaysForcePOT = true;
  71679. _this._blurX.autoClear = false;
  71680. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  71681. _this._blurY.alwaysForcePOT = true;
  71682. _this._blurY.autoClear = false;
  71683. _this.kernel = bloomKernel;
  71684. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  71685. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71686. _this._merge.autoClear = false;
  71687. _this._effects.push(_this._merge);
  71688. return _this;
  71689. }
  71690. Object.defineProperty(BloomEffect.prototype, "threshold", {
  71691. /**
  71692. * The luminance threshold to find bright areas of the image to bloom.
  71693. */
  71694. get: function () {
  71695. return this._downscale.threshold;
  71696. },
  71697. set: function (value) {
  71698. this._downscale.threshold = value;
  71699. },
  71700. enumerable: true,
  71701. configurable: true
  71702. });
  71703. Object.defineProperty(BloomEffect.prototype, "weight", {
  71704. /**
  71705. * The strength of the bloom.
  71706. */
  71707. get: function () {
  71708. return this._merge.weight;
  71709. },
  71710. set: function (value) {
  71711. this._merge.weight = value;
  71712. },
  71713. enumerable: true,
  71714. configurable: true
  71715. });
  71716. Object.defineProperty(BloomEffect.prototype, "kernel", {
  71717. /**
  71718. * Specifies the size of the bloom blur kernel, relative to the final output size
  71719. */
  71720. get: function () {
  71721. return this._blurX.kernel / this.bloomScale;
  71722. },
  71723. set: function (value) {
  71724. this._blurX.kernel = value * this.bloomScale;
  71725. this._blurY.kernel = value * this.bloomScale;
  71726. },
  71727. enumerable: true,
  71728. configurable: true
  71729. });
  71730. /**
  71731. * Disposes each of the internal effects for a given camera.
  71732. * @param camera The camera to dispose the effect on.
  71733. */
  71734. BloomEffect.prototype.disposeEffects = function (camera) {
  71735. for (var effect in this._effects) {
  71736. this._effects[effect].dispose(camera);
  71737. }
  71738. };
  71739. /**
  71740. * Internal
  71741. */
  71742. BloomEffect.prototype._updateEffects = function () {
  71743. for (var effect in this._effects) {
  71744. this._effects[effect].updateEffect();
  71745. }
  71746. };
  71747. /**
  71748. * Internal
  71749. * @returns if all the contained post processes are ready.
  71750. */
  71751. BloomEffect.prototype._isReady = function () {
  71752. for (var effect in this._effects) {
  71753. if (!this._effects[effect].isReady()) {
  71754. return false;
  71755. }
  71756. }
  71757. return true;
  71758. };
  71759. return BloomEffect;
  71760. }(BABYLON.PostProcessRenderEffect));
  71761. BABYLON.BloomEffect = BloomEffect;
  71762. })(BABYLON || (BABYLON = {}));
  71763. //# sourceMappingURL=babylon.bloomEffect.js.map
  71764. "use strict";
  71765. var BABYLON;
  71766. (function (BABYLON) {
  71767. /**
  71768. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  71769. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  71770. */
  71771. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  71772. __extends(DefaultRenderingPipeline, _super);
  71773. /**
  71774. * @constructor
  71775. * @param {string} name - The rendering pipeline name
  71776. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71777. * @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)
  71778. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71779. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  71780. */
  71781. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  71782. if (automaticBuild === void 0) { automaticBuild = true; }
  71783. var _this = _super.call(this, scene.getEngine(), name) || this;
  71784. _this._originalCameras = [];
  71785. /**
  71786. * ID of the sharpen post process,
  71787. */
  71788. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  71789. /**
  71790. * ID of the image processing post process;
  71791. */
  71792. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  71793. /**
  71794. * ID of the Fast Approximate Anti-Aliasing post process;
  71795. */
  71796. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  71797. /**
  71798. * ID of the chromatic aberration post process,
  71799. */
  71800. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  71801. /**
  71802. * ID of the grain post process
  71803. */
  71804. _this.GrainPostProcessId = "GrainPostProcessEffect";
  71805. /**
  71806. * Animations which can be used to tweak settings over a period of time
  71807. */
  71808. _this.animations = [];
  71809. _this._imageProcessingConfigurationObserver = null;
  71810. // Values
  71811. _this._sharpenEnabled = false;
  71812. _this._bloomEnabled = false;
  71813. _this._depthOfFieldEnabled = false;
  71814. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  71815. _this._fxaaEnabled = false;
  71816. _this._imageProcessingEnabled = true;
  71817. _this._bloomScale = 0.5;
  71818. _this._chromaticAberrationEnabled = false;
  71819. _this._grainEnabled = false;
  71820. _this._buildAllowed = true;
  71821. _this._resizeObserver = null;
  71822. _this._hardwareScaleLevel = 1.0;
  71823. _this._bloomKernel = 64;
  71824. /**
  71825. * Specifies the weight of the bloom in the final rendering
  71826. */
  71827. _this._bloomWeight = 0.15;
  71828. /**
  71829. * Specifies the luma threshold for the area that will be blurred by the bloom
  71830. */
  71831. _this._bloomThreshold = 0.9;
  71832. _this._samples = 1;
  71833. _this._hasCleared = false;
  71834. _this._prevPostProcess = null;
  71835. _this._prevPrevPostProcess = null;
  71836. _this._cameras = cameras || [];
  71837. _this._originalCameras = _this._cameras.slice();
  71838. _this._buildAllowed = automaticBuild;
  71839. // Initialize
  71840. _this._scene = scene;
  71841. var caps = _this._scene.getEngine().getCaps();
  71842. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  71843. // Misc
  71844. if (_this._hdr) {
  71845. if (caps.textureHalfFloatRender) {
  71846. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71847. }
  71848. else if (caps.textureFloatRender) {
  71849. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71850. }
  71851. }
  71852. else {
  71853. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71854. }
  71855. // Attach
  71856. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71857. var engine = _this._scene.getEngine();
  71858. // Create post processes before hand so they can be modified before enabled.
  71859. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  71860. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  71861. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  71862. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  71863. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  71864. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  71865. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  71866. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  71867. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  71868. _this._resizeObserver = engine.onResizeObservable.add(function () {
  71869. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  71870. _this.bloomKernel = _this.bloomKernel;
  71871. });
  71872. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  71873. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  71874. });
  71875. _this._buildPipeline();
  71876. return _this;
  71877. }
  71878. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  71879. get: function () {
  71880. return this._sharpenEnabled;
  71881. },
  71882. /**
  71883. * Enable or disable the sharpen process from the pipeline
  71884. */
  71885. set: function (enabled) {
  71886. if (this._sharpenEnabled === enabled) {
  71887. return;
  71888. }
  71889. this._sharpenEnabled = enabled;
  71890. this._buildPipeline();
  71891. },
  71892. enumerable: true,
  71893. configurable: true
  71894. });
  71895. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  71896. /**
  71897. * Specifies the size of the bloom blur kernel, relative to the final output size
  71898. */
  71899. get: function () {
  71900. return this._bloomKernel;
  71901. },
  71902. set: function (value) {
  71903. this._bloomKernel = value;
  71904. this.bloom.kernel = value / this._hardwareScaleLevel;
  71905. },
  71906. enumerable: true,
  71907. configurable: true
  71908. });
  71909. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  71910. get: function () {
  71911. return this._bloomWeight;
  71912. },
  71913. /**
  71914. * The strength of the bloom.
  71915. */
  71916. set: function (value) {
  71917. if (this._bloomWeight === value) {
  71918. return;
  71919. }
  71920. this.bloom.weight = value;
  71921. this._bloomWeight = value;
  71922. },
  71923. enumerable: true,
  71924. configurable: true
  71925. });
  71926. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  71927. get: function () {
  71928. return this._bloomThreshold;
  71929. },
  71930. /**
  71931. * The strength of the bloom.
  71932. */
  71933. set: function (value) {
  71934. if (this._bloomThreshold === value) {
  71935. return;
  71936. }
  71937. this.bloom.threshold = value;
  71938. this._bloomThreshold = value;
  71939. },
  71940. enumerable: true,
  71941. configurable: true
  71942. });
  71943. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  71944. get: function () {
  71945. return this._bloomScale;
  71946. },
  71947. /**
  71948. * The scale of the bloom, lower value will provide better performance.
  71949. */
  71950. set: function (value) {
  71951. if (this._bloomScale === value) {
  71952. return;
  71953. }
  71954. this._bloomScale = value;
  71955. // recreate bloom and dispose old as this setting is not dynamic
  71956. this._rebuildBloom();
  71957. this._buildPipeline();
  71958. },
  71959. enumerable: true,
  71960. configurable: true
  71961. });
  71962. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  71963. get: function () {
  71964. return this._bloomEnabled;
  71965. },
  71966. /**
  71967. * Enable or disable the bloom from the pipeline
  71968. */
  71969. set: function (enabled) {
  71970. if (this._bloomEnabled === enabled) {
  71971. return;
  71972. }
  71973. this._bloomEnabled = enabled;
  71974. this._buildPipeline();
  71975. },
  71976. enumerable: true,
  71977. configurable: true
  71978. });
  71979. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  71980. // recreate bloom and dispose old as this setting is not dynamic
  71981. var oldBloom = this.bloom;
  71982. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  71983. this.bloom.threshold = oldBloom.threshold;
  71984. for (var i = 0; i < this._cameras.length; i++) {
  71985. oldBloom.disposeEffects(this._cameras[i]);
  71986. }
  71987. };
  71988. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  71989. /**
  71990. * If the depth of field is enabled.
  71991. */
  71992. get: function () {
  71993. return this._depthOfFieldEnabled;
  71994. },
  71995. set: function (enabled) {
  71996. if (this._depthOfFieldEnabled === enabled) {
  71997. return;
  71998. }
  71999. this._depthOfFieldEnabled = enabled;
  72000. this._buildPipeline();
  72001. },
  72002. enumerable: true,
  72003. configurable: true
  72004. });
  72005. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  72006. /**
  72007. * Blur level of the depth of field effect. (Higher blur will effect performance)
  72008. */
  72009. get: function () {
  72010. return this._depthOfFieldBlurLevel;
  72011. },
  72012. set: function (value) {
  72013. if (this._depthOfFieldBlurLevel === value) {
  72014. return;
  72015. }
  72016. this._depthOfFieldBlurLevel = value;
  72017. // recreate dof and dispose old as this setting is not dynamic
  72018. var oldDof = this.depthOfField;
  72019. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  72020. this.depthOfField.focalLength = oldDof.focalLength;
  72021. this.depthOfField.focusDistance = oldDof.focusDistance;
  72022. this.depthOfField.fStop = oldDof.fStop;
  72023. this.depthOfField.lensSize = oldDof.lensSize;
  72024. for (var i = 0; i < this._cameras.length; i++) {
  72025. oldDof.disposeEffects(this._cameras[i]);
  72026. }
  72027. this._buildPipeline();
  72028. },
  72029. enumerable: true,
  72030. configurable: true
  72031. });
  72032. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  72033. get: function () {
  72034. return this._fxaaEnabled;
  72035. },
  72036. /**
  72037. * If the anti aliasing is enabled.
  72038. */
  72039. set: function (enabled) {
  72040. if (this._fxaaEnabled === enabled) {
  72041. return;
  72042. }
  72043. this._fxaaEnabled = enabled;
  72044. this._buildPipeline();
  72045. },
  72046. enumerable: true,
  72047. configurable: true
  72048. });
  72049. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  72050. get: function () {
  72051. return this._samples;
  72052. },
  72053. /**
  72054. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  72055. */
  72056. set: function (sampleCount) {
  72057. if (this._samples === sampleCount) {
  72058. return;
  72059. }
  72060. this._samples = sampleCount;
  72061. this._buildPipeline();
  72062. },
  72063. enumerable: true,
  72064. configurable: true
  72065. });
  72066. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  72067. get: function () {
  72068. return this._imageProcessingEnabled;
  72069. },
  72070. /**
  72071. * If image processing is enabled.
  72072. */
  72073. set: function (enabled) {
  72074. if (this._imageProcessingEnabled === enabled) {
  72075. return;
  72076. }
  72077. this._imageProcessingEnabled = enabled;
  72078. this._buildPipeline();
  72079. },
  72080. enumerable: true,
  72081. configurable: true
  72082. });
  72083. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  72084. get: function () {
  72085. return this._chromaticAberrationEnabled;
  72086. },
  72087. /**
  72088. * Enable or disable the chromaticAberration process from the pipeline
  72089. */
  72090. set: function (enabled) {
  72091. if (this._chromaticAberrationEnabled === enabled) {
  72092. return;
  72093. }
  72094. this._chromaticAberrationEnabled = enabled;
  72095. this._buildPipeline();
  72096. },
  72097. enumerable: true,
  72098. configurable: true
  72099. });
  72100. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  72101. get: function () {
  72102. return this._grainEnabled;
  72103. },
  72104. /**
  72105. * Enable or disable the grain process from the pipeline
  72106. */
  72107. set: function (enabled) {
  72108. if (this._grainEnabled === enabled) {
  72109. return;
  72110. }
  72111. this._grainEnabled = enabled;
  72112. this._buildPipeline();
  72113. },
  72114. enumerable: true,
  72115. configurable: true
  72116. });
  72117. /**
  72118. * Force the compilation of the entire pipeline.
  72119. */
  72120. DefaultRenderingPipeline.prototype.prepare = function () {
  72121. var previousState = this._buildAllowed;
  72122. this._buildAllowed = true;
  72123. this._buildPipeline();
  72124. this._buildAllowed = previousState;
  72125. };
  72126. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  72127. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  72128. if (this._hasCleared) {
  72129. postProcess.autoClear = false;
  72130. }
  72131. else {
  72132. postProcess.autoClear = true;
  72133. this._scene.autoClear = false;
  72134. this._hasCleared = true;
  72135. }
  72136. if (!skipTextureSharing) {
  72137. if (this._prevPrevPostProcess) {
  72138. postProcess.shareOutputWith(this._prevPrevPostProcess);
  72139. }
  72140. else {
  72141. postProcess.useOwnOutput();
  72142. }
  72143. if (this._prevPostProcess) {
  72144. this._prevPrevPostProcess = this._prevPostProcess;
  72145. }
  72146. this._prevPostProcess = postProcess;
  72147. }
  72148. };
  72149. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  72150. var _this = this;
  72151. if (!this._buildAllowed) {
  72152. return;
  72153. }
  72154. this._scene.autoClear = true;
  72155. var engine = this._scene.getEngine();
  72156. this._disposePostProcesses();
  72157. if (this._cameras !== null) {
  72158. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72159. // get back cameras to be used to reattach pipeline
  72160. this._cameras = this._originalCameras.slice();
  72161. }
  72162. this._reset();
  72163. this._prevPostProcess = null;
  72164. this._prevPrevPostProcess = null;
  72165. this._hasCleared = false;
  72166. if (this.depthOfFieldEnabled) {
  72167. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  72168. this.depthOfField.depthTexture = depthTexture;
  72169. if (!this.depthOfField._isReady()) {
  72170. this.depthOfField._updateEffects();
  72171. }
  72172. this.addEffect(this.depthOfField);
  72173. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  72174. }
  72175. if (this.bloomEnabled) {
  72176. if (!this.bloom._isReady()) {
  72177. this.bloom._updateEffects();
  72178. }
  72179. this.addEffect(this.bloom);
  72180. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  72181. }
  72182. if (this._imageProcessingEnabled) {
  72183. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  72184. if (this._hdr) {
  72185. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  72186. this._setAutoClearAndTextureSharing(this.imageProcessing);
  72187. }
  72188. else {
  72189. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  72190. }
  72191. }
  72192. if (this.sharpenEnabled) {
  72193. if (!this.sharpen.isReady()) {
  72194. this.sharpen.updateEffect();
  72195. }
  72196. this.addEffect(this._sharpenEffect);
  72197. this._setAutoClearAndTextureSharing(this.sharpen);
  72198. }
  72199. if (this.grainEnabled) {
  72200. if (!this.grain.isReady()) {
  72201. this.grain.updateEffect();
  72202. }
  72203. this.addEffect(this._grainEffect);
  72204. this._setAutoClearAndTextureSharing(this.grain);
  72205. }
  72206. if (this.chromaticAberrationEnabled) {
  72207. if (!this.chromaticAberration.isReady()) {
  72208. this.chromaticAberration.updateEffect();
  72209. }
  72210. this.addEffect(this._chromaticAberrationEffect);
  72211. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  72212. }
  72213. if (this.fxaaEnabled) {
  72214. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  72215. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  72216. this._setAutoClearAndTextureSharing(this.fxaa, true);
  72217. }
  72218. if (this._cameras !== null) {
  72219. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  72220. }
  72221. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  72222. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  72223. }
  72224. };
  72225. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  72226. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  72227. for (var i = 0; i < this._cameras.length; i++) {
  72228. var camera = this._cameras[i];
  72229. if (this.imageProcessing) {
  72230. this.imageProcessing.dispose(camera);
  72231. }
  72232. if (this.fxaa) {
  72233. this.fxaa.dispose(camera);
  72234. }
  72235. // These are created in the constructor and should not be disposed on every pipeline change
  72236. if (disposeNonRecreated) {
  72237. if (this.sharpen) {
  72238. this.sharpen.dispose(camera);
  72239. }
  72240. if (this.depthOfField) {
  72241. this.depthOfField.disposeEffects(camera);
  72242. }
  72243. if (this.bloom) {
  72244. this.bloom.disposeEffects(camera);
  72245. }
  72246. if (this.chromaticAberration) {
  72247. this.chromaticAberration.dispose(camera);
  72248. }
  72249. if (this.grain) {
  72250. this.grain.dispose(camera);
  72251. }
  72252. }
  72253. }
  72254. this.imageProcessing = null;
  72255. this.fxaa = null;
  72256. if (disposeNonRecreated) {
  72257. this.sharpen = null;
  72258. this._sharpenEffect = null;
  72259. this.depthOfField = null;
  72260. this.bloom = null;
  72261. this.chromaticAberration = null;
  72262. this._chromaticAberrationEffect = null;
  72263. this.grain = null;
  72264. this._grainEffect = null;
  72265. }
  72266. };
  72267. /**
  72268. * Dispose of the pipeline and stop all post processes
  72269. */
  72270. DefaultRenderingPipeline.prototype.dispose = function () {
  72271. this._disposePostProcesses(true);
  72272. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72273. this._scene.autoClear = true;
  72274. if (this._resizeObserver) {
  72275. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  72276. this._resizeObserver = null;
  72277. }
  72278. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  72279. _super.prototype.dispose.call(this);
  72280. };
  72281. /**
  72282. * Serialize the rendering pipeline (Used when exporting)
  72283. * @returns the serialized object
  72284. */
  72285. DefaultRenderingPipeline.prototype.serialize = function () {
  72286. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72287. serializationObject.customType = "DefaultRenderingPipeline";
  72288. return serializationObject;
  72289. };
  72290. /**
  72291. * Parse the serialized pipeline
  72292. * @param source Source pipeline.
  72293. * @param scene The scene to load the pipeline to.
  72294. * @param rootUrl The URL of the serialized pipeline.
  72295. * @returns An instantiated pipeline from the serialized object.
  72296. */
  72297. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  72298. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  72299. };
  72300. __decorate([
  72301. BABYLON.serialize()
  72302. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  72303. __decorate([
  72304. BABYLON.serialize()
  72305. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  72306. __decorate([
  72307. BABYLON.serialize()
  72308. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  72309. __decorate([
  72310. BABYLON.serialize()
  72311. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  72312. __decorate([
  72313. BABYLON.serialize()
  72314. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  72315. __decorate([
  72316. BABYLON.serialize()
  72317. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  72318. __decorate([
  72319. BABYLON.serialize()
  72320. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  72321. __decorate([
  72322. BABYLON.serialize()
  72323. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  72324. __decorate([
  72325. BABYLON.serialize()
  72326. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  72327. __decorate([
  72328. BABYLON.serialize()
  72329. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  72330. __decorate([
  72331. BABYLON.serialize()
  72332. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  72333. __decorate([
  72334. BABYLON.serialize()
  72335. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  72336. __decorate([
  72337. BABYLON.serialize()
  72338. ], DefaultRenderingPipeline.prototype, "samples", null);
  72339. __decorate([
  72340. BABYLON.serialize()
  72341. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  72342. __decorate([
  72343. BABYLON.serialize()
  72344. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  72345. __decorate([
  72346. BABYLON.serialize()
  72347. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  72348. return DefaultRenderingPipeline;
  72349. }(BABYLON.PostProcessRenderPipeline));
  72350. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  72351. })(BABYLON || (BABYLON = {}));
  72352. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  72353. "use strict";
  72354. var BABYLON;
  72355. (function (BABYLON) {
  72356. /**
  72357. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  72358. */
  72359. var GeometryBufferRenderer = /** @class */ (function () {
  72360. /**
  72361. * Creates a new G Buffer for the scene
  72362. * @param scene The scene the buffer belongs to
  72363. * @param ratio How big is the buffer related to the main canvas.
  72364. */
  72365. function GeometryBufferRenderer(scene, ratio) {
  72366. if (ratio === void 0) { ratio = 1; }
  72367. this._enablePosition = false;
  72368. this._scene = scene;
  72369. this._ratio = ratio;
  72370. // Render target
  72371. this._createRenderTargets();
  72372. }
  72373. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  72374. /**
  72375. * Set the render list (meshes to be rendered) used in the G buffer.
  72376. */
  72377. set: function (meshes) {
  72378. this._multiRenderTarget.renderList = meshes;
  72379. },
  72380. enumerable: true,
  72381. configurable: true
  72382. });
  72383. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  72384. /**
  72385. * Gets wether or not G buffer are supported by the running hardware.
  72386. * This requires draw buffer supports
  72387. */
  72388. get: function () {
  72389. return this._multiRenderTarget.isSupported;
  72390. },
  72391. enumerable: true,
  72392. configurable: true
  72393. });
  72394. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  72395. /**
  72396. * Gets wether or not position are enabled for the G buffer.
  72397. */
  72398. get: function () {
  72399. return this._enablePosition;
  72400. },
  72401. /**
  72402. * Sets wether or not position are enabled for the G buffer.
  72403. */
  72404. set: function (enable) {
  72405. this._enablePosition = enable;
  72406. this.dispose();
  72407. this._createRenderTargets();
  72408. },
  72409. enumerable: true,
  72410. configurable: true
  72411. });
  72412. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  72413. /**
  72414. * Gets the scene associated with the buffer.
  72415. */
  72416. get: function () {
  72417. return this._scene;
  72418. },
  72419. enumerable: true,
  72420. configurable: true
  72421. });
  72422. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  72423. /**
  72424. * Gets the ratio used by the buffer during its creation.
  72425. * How big is the buffer related to the main canvas.
  72426. */
  72427. get: function () {
  72428. return this._ratio;
  72429. },
  72430. enumerable: true,
  72431. configurable: true
  72432. });
  72433. /**
  72434. * Checks wether everything is ready to render a submesh to the G buffer.
  72435. * @param subMesh the submesh to check readiness for
  72436. * @param useInstances is the mesh drawn using instance or not
  72437. * @returns true if ready otherwise false
  72438. */
  72439. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  72440. var material = subMesh.getMaterial();
  72441. if (material && material.disableDepthWrite) {
  72442. return false;
  72443. }
  72444. var defines = [];
  72445. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72446. var mesh = subMesh.getMesh();
  72447. // Alpha test
  72448. if (material && material.needAlphaTesting()) {
  72449. defines.push("#define ALPHATEST");
  72450. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72451. attribs.push(BABYLON.VertexBuffer.UVKind);
  72452. defines.push("#define UV1");
  72453. }
  72454. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72455. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72456. defines.push("#define UV2");
  72457. }
  72458. }
  72459. // Buffers
  72460. if (this._enablePosition) {
  72461. defines.push("#define POSITION");
  72462. }
  72463. // Bones
  72464. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72465. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72466. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72467. if (mesh.numBoneInfluencers > 4) {
  72468. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72469. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72470. }
  72471. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72472. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72473. }
  72474. else {
  72475. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72476. }
  72477. // Instances
  72478. if (useInstances) {
  72479. defines.push("#define INSTANCES");
  72480. attribs.push("world0");
  72481. attribs.push("world1");
  72482. attribs.push("world2");
  72483. attribs.push("world3");
  72484. }
  72485. // Get correct effect
  72486. var join = defines.join("\n");
  72487. if (this._cachedDefines !== join) {
  72488. this._cachedDefines = join;
  72489. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  72490. }
  72491. return this._effect.isReady();
  72492. };
  72493. /**
  72494. * Gets the current underlying G Buffer.
  72495. * @returns the buffer
  72496. */
  72497. GeometryBufferRenderer.prototype.getGBuffer = function () {
  72498. return this._multiRenderTarget;
  72499. };
  72500. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  72501. /**
  72502. * Gets the number of samples used to render the buffer (anti aliasing).
  72503. */
  72504. get: function () {
  72505. return this._multiRenderTarget.samples;
  72506. },
  72507. /**
  72508. * Sets the number of samples used to render the buffer (anti aliasing).
  72509. */
  72510. set: function (value) {
  72511. this._multiRenderTarget.samples = value;
  72512. },
  72513. enumerable: true,
  72514. configurable: true
  72515. });
  72516. /**
  72517. * Disposes the renderer and frees up associated resources.
  72518. */
  72519. GeometryBufferRenderer.prototype.dispose = function () {
  72520. this.getGBuffer().dispose();
  72521. };
  72522. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  72523. var _this = this;
  72524. var engine = this._scene.getEngine();
  72525. var count = this._enablePosition ? 3 : 2;
  72526. 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 });
  72527. if (!this.isSupported) {
  72528. return;
  72529. }
  72530. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72531. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72532. this._multiRenderTarget.refreshRate = 1;
  72533. this._multiRenderTarget.renderParticles = false;
  72534. this._multiRenderTarget.renderList = null;
  72535. // set default depth value to 1.0 (far away)
  72536. this._multiRenderTarget.onClearObservable.add(function (engine) {
  72537. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  72538. });
  72539. // Custom render function
  72540. var renderSubMesh = function (subMesh) {
  72541. var mesh = subMesh.getRenderingMesh();
  72542. var scene = _this._scene;
  72543. var engine = scene.getEngine();
  72544. var material = subMesh.getMaterial();
  72545. if (!material) {
  72546. return;
  72547. }
  72548. // Culling
  72549. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72550. // Managing instances
  72551. var batch = mesh._getInstancesRenderList(subMesh._id);
  72552. if (batch.mustReturn) {
  72553. return;
  72554. }
  72555. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72556. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  72557. engine.enableEffect(_this._effect);
  72558. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72559. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72560. _this._effect.setMatrix("view", scene.getViewMatrix());
  72561. // Alpha test
  72562. if (material && material.needAlphaTesting()) {
  72563. var alphaTexture = material.getAlphaTestTexture();
  72564. if (alphaTexture) {
  72565. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72566. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72567. }
  72568. }
  72569. // Bones
  72570. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72571. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72572. }
  72573. // Draw
  72574. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72575. }
  72576. };
  72577. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72578. var index;
  72579. if (depthOnlySubMeshes.length) {
  72580. engine.setColorWrite(false);
  72581. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72582. renderSubMesh(depthOnlySubMeshes.data[index]);
  72583. }
  72584. engine.setColorWrite(true);
  72585. }
  72586. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72587. renderSubMesh(opaqueSubMeshes.data[index]);
  72588. }
  72589. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72590. renderSubMesh(alphaTestSubMeshes.data[index]);
  72591. }
  72592. };
  72593. };
  72594. return GeometryBufferRenderer;
  72595. }());
  72596. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  72597. })(BABYLON || (BABYLON = {}));
  72598. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  72599. "use strict";
  72600. var BABYLON;
  72601. (function (BABYLON) {
  72602. var RefractionPostProcess = /** @class */ (function (_super) {
  72603. __extends(RefractionPostProcess, _super);
  72604. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  72605. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  72606. _this.color = color;
  72607. _this.depth = depth;
  72608. _this.colorLevel = colorLevel;
  72609. _this._ownRefractionTexture = true;
  72610. _this.onActivateObservable.add(function (cam) {
  72611. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  72612. });
  72613. _this.onApplyObservable.add(function (effect) {
  72614. effect.setColor3("baseColor", _this.color);
  72615. effect.setFloat("depth", _this.depth);
  72616. effect.setFloat("colorLevel", _this.colorLevel);
  72617. effect.setTexture("refractionSampler", _this._refTexture);
  72618. });
  72619. return _this;
  72620. }
  72621. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  72622. /**
  72623. * Gets or sets the refraction texture
  72624. * Please note that you are responsible for disposing the texture if you set it manually
  72625. */
  72626. get: function () {
  72627. return this._refTexture;
  72628. },
  72629. set: function (value) {
  72630. if (this._refTexture && this._ownRefractionTexture) {
  72631. this._refTexture.dispose();
  72632. }
  72633. this._refTexture = value;
  72634. this._ownRefractionTexture = false;
  72635. },
  72636. enumerable: true,
  72637. configurable: true
  72638. });
  72639. // Methods
  72640. RefractionPostProcess.prototype.dispose = function (camera) {
  72641. if (this._refTexture && this._ownRefractionTexture) {
  72642. this._refTexture.dispose();
  72643. this._refTexture = null;
  72644. }
  72645. _super.prototype.dispose.call(this, camera);
  72646. };
  72647. return RefractionPostProcess;
  72648. }(BABYLON.PostProcess));
  72649. BABYLON.RefractionPostProcess = RefractionPostProcess;
  72650. })(BABYLON || (BABYLON = {}));
  72651. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  72652. "use strict";
  72653. var BABYLON;
  72654. (function (BABYLON) {
  72655. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  72656. __extends(BlackAndWhitePostProcess, _super);
  72657. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  72658. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  72659. _this.degree = 1;
  72660. _this.onApplyObservable.add(function (effect) {
  72661. effect.setFloat("degree", _this.degree);
  72662. });
  72663. return _this;
  72664. }
  72665. return BlackAndWhitePostProcess;
  72666. }(BABYLON.PostProcess));
  72667. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  72668. })(BABYLON || (BABYLON = {}));
  72669. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  72670. "use strict";
  72671. var BABYLON;
  72672. (function (BABYLON) {
  72673. /**
  72674. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  72675. * input texture to perform effects such as edge detection or sharpening
  72676. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  72677. */
  72678. var ConvolutionPostProcess = /** @class */ (function (_super) {
  72679. __extends(ConvolutionPostProcess, _super);
  72680. /**
  72681. * Creates a new instance ConvolutionPostProcess
  72682. * @param name The name of the effect.
  72683. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  72684. * @param options The required width/height ratio to downsize to before computing the render pass.
  72685. * @param camera The camera to apply the render pass to.
  72686. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72687. * @param engine The engine which the post process will be applied. (default: current engine)
  72688. * @param reusable If the post process can be reused on the same frame. (default: false)
  72689. * @param textureType Type of textures used when performing the post process. (default: 0)
  72690. */
  72691. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  72692. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72693. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72694. _this.kernel = kernel;
  72695. _this.onApply = function (effect) {
  72696. effect.setFloat2("screenSize", _this.width, _this.height);
  72697. effect.setArray("kernel", _this.kernel);
  72698. };
  72699. return _this;
  72700. }
  72701. // Statics
  72702. /**
  72703. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72704. */
  72705. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  72706. /**
  72707. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72708. */
  72709. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  72710. /**
  72711. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72712. */
  72713. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  72714. /**
  72715. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72716. */
  72717. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  72718. /**
  72719. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72720. */
  72721. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  72722. /**
  72723. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72724. */
  72725. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  72726. return ConvolutionPostProcess;
  72727. }(BABYLON.PostProcess));
  72728. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  72729. })(BABYLON || (BABYLON = {}));
  72730. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  72731. "use strict";
  72732. var BABYLON;
  72733. (function (BABYLON) {
  72734. var FilterPostProcess = /** @class */ (function (_super) {
  72735. __extends(FilterPostProcess, _super);
  72736. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  72737. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  72738. _this.kernelMatrix = kernelMatrix;
  72739. _this.onApply = function (effect) {
  72740. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  72741. };
  72742. return _this;
  72743. }
  72744. return FilterPostProcess;
  72745. }(BABYLON.PostProcess));
  72746. BABYLON.FilterPostProcess = FilterPostProcess;
  72747. })(BABYLON || (BABYLON = {}));
  72748. //# sourceMappingURL=babylon.filterPostProcess.js.map
  72749. "use strict";
  72750. var BABYLON;
  72751. (function (BABYLON) {
  72752. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  72753. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  72754. __extends(VolumetricLightScatteringPostProcess, _super);
  72755. /**
  72756. * @constructor
  72757. * @param {string} name - The post-process name
  72758. * @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)
  72759. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  72760. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  72761. * @param {number} samples - The post-process quality, default 100
  72762. * @param {number} samplingMode - The post-process filtering mode
  72763. * @param {BABYLON.Engine} engine - The babylon engine
  72764. * @param {boolean} reusable - If the post-process is reusable
  72765. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  72766. */
  72767. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  72768. if (samples === void 0) { samples = 100; }
  72769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72770. 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;
  72771. _this._screenCoordinates = BABYLON.Vector2.Zero();
  72772. /**
  72773. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  72774. */
  72775. _this.customMeshPosition = BABYLON.Vector3.Zero();
  72776. /**
  72777. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  72778. */
  72779. _this.useCustomMeshPosition = false;
  72780. /**
  72781. * If the post-process should inverse the light scattering direction
  72782. */
  72783. _this.invert = true;
  72784. /**
  72785. * Array containing the excluded meshes not rendered in the internal pass
  72786. */
  72787. _this.excludedMeshes = new Array();
  72788. /**
  72789. * Controls the overall intensity of the post-process
  72790. */
  72791. _this.exposure = 0.3;
  72792. /**
  72793. * Dissipates each sample's contribution in range [0, 1]
  72794. */
  72795. _this.decay = 0.96815;
  72796. /**
  72797. * Controls the overall intensity of each sample
  72798. */
  72799. _this.weight = 0.58767;
  72800. /**
  72801. * Controls the density of each sample
  72802. */
  72803. _this.density = 0.926;
  72804. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  72805. engine = scene.getEngine();
  72806. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  72807. // Configure mesh
  72808. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  72809. // Configure
  72810. _this._createPass(scene, ratio.passRatio || ratio);
  72811. _this.onActivate = function (camera) {
  72812. if (!_this.isSupported) {
  72813. _this.dispose(camera);
  72814. }
  72815. _this.onActivate = null;
  72816. };
  72817. _this.onApplyObservable.add(function (effect) {
  72818. _this._updateMeshScreenCoordinates(scene);
  72819. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  72820. effect.setFloat("exposure", _this.exposure);
  72821. effect.setFloat("decay", _this.decay);
  72822. effect.setFloat("weight", _this.weight);
  72823. effect.setFloat("density", _this.density);
  72824. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  72825. });
  72826. return _this;
  72827. }
  72828. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  72829. get: function () {
  72830. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  72831. return false;
  72832. },
  72833. set: function (useDiffuseColor) {
  72834. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  72835. },
  72836. enumerable: true,
  72837. configurable: true
  72838. });
  72839. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  72840. return "VolumetricLightScatteringPostProcess";
  72841. };
  72842. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  72843. var mesh = subMesh.getMesh();
  72844. // Render this.mesh as default
  72845. if (mesh === this.mesh && mesh.material) {
  72846. return mesh.material.isReady(mesh);
  72847. }
  72848. var defines = [];
  72849. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72850. var material = subMesh.getMaterial();
  72851. // Alpha test
  72852. if (material) {
  72853. if (material.needAlphaTesting()) {
  72854. defines.push("#define ALPHATEST");
  72855. }
  72856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72857. attribs.push(BABYLON.VertexBuffer.UVKind);
  72858. defines.push("#define UV1");
  72859. }
  72860. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72861. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72862. defines.push("#define UV2");
  72863. }
  72864. }
  72865. // Bones
  72866. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72867. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72868. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72869. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72870. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72871. }
  72872. else {
  72873. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72874. }
  72875. // Instances
  72876. if (useInstances) {
  72877. defines.push("#define INSTANCES");
  72878. attribs.push("world0");
  72879. attribs.push("world1");
  72880. attribs.push("world2");
  72881. attribs.push("world3");
  72882. }
  72883. // Get correct effect
  72884. var join = defines.join("\n");
  72885. if (this._cachedDefines !== join) {
  72886. this._cachedDefines = join;
  72887. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  72888. }
  72889. return this._volumetricLightScatteringPass.isReady();
  72890. };
  72891. /**
  72892. * Sets the new light position for light scattering effect
  72893. * @param {BABYLON.Vector3} The new custom light position
  72894. */
  72895. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  72896. this.customMeshPosition = position;
  72897. };
  72898. /**
  72899. * Returns the light position for light scattering effect
  72900. * @return {BABYLON.Vector3} The custom light position
  72901. */
  72902. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  72903. return this.customMeshPosition;
  72904. };
  72905. /**
  72906. * Disposes the internal assets and detaches the post-process from the camera
  72907. */
  72908. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  72909. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  72910. if (rttIndex !== -1) {
  72911. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  72912. }
  72913. this._volumetricLightScatteringRTT.dispose();
  72914. _super.prototype.dispose.call(this, camera);
  72915. };
  72916. /**
  72917. * Returns the render target texture used by the post-process
  72918. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  72919. */
  72920. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  72921. return this._volumetricLightScatteringRTT;
  72922. };
  72923. // Private methods
  72924. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  72925. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  72926. return true;
  72927. }
  72928. return false;
  72929. };
  72930. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  72931. var _this = this;
  72932. var engine = scene.getEngine();
  72933. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72934. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72935. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72936. this._volumetricLightScatteringRTT.renderList = null;
  72937. this._volumetricLightScatteringRTT.renderParticles = false;
  72938. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  72939. var camera = this.getCamera();
  72940. if (camera) {
  72941. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  72942. }
  72943. else {
  72944. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  72945. }
  72946. // Custom render function for submeshes
  72947. var renderSubMesh = function (subMesh) {
  72948. var mesh = subMesh.getRenderingMesh();
  72949. if (_this._meshExcluded(mesh)) {
  72950. return;
  72951. }
  72952. var material = subMesh.getMaterial();
  72953. if (!material) {
  72954. return;
  72955. }
  72956. var scene = mesh.getScene();
  72957. var engine = scene.getEngine();
  72958. // Culling
  72959. engine.setState(material.backFaceCulling);
  72960. // Managing instances
  72961. var batch = mesh._getInstancesRenderList(subMesh._id);
  72962. if (batch.mustReturn) {
  72963. return;
  72964. }
  72965. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72966. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  72967. var effect = _this._volumetricLightScatteringPass;
  72968. if (mesh === _this.mesh) {
  72969. if (subMesh.effect) {
  72970. effect = subMesh.effect;
  72971. }
  72972. else {
  72973. effect = material.getEffect();
  72974. }
  72975. }
  72976. engine.enableEffect(effect);
  72977. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  72978. if (mesh === _this.mesh) {
  72979. material.bind(mesh.getWorldMatrix(), mesh);
  72980. }
  72981. else {
  72982. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  72983. // Alpha test
  72984. if (material && material.needAlphaTesting()) {
  72985. var alphaTexture = material.getAlphaTestTexture();
  72986. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  72987. if (alphaTexture) {
  72988. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72989. }
  72990. }
  72991. // Bones
  72992. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72993. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72994. }
  72995. }
  72996. // Draw
  72997. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  72998. }
  72999. };
  73000. // Render target texture callbacks
  73001. var savedSceneClearColor;
  73002. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  73003. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  73004. savedSceneClearColor = scene.clearColor;
  73005. scene.clearColor = sceneClearColor;
  73006. });
  73007. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  73008. scene.clearColor = savedSceneClearColor;
  73009. });
  73010. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73011. var engine = scene.getEngine();
  73012. var index;
  73013. if (depthOnlySubMeshes.length) {
  73014. engine.setColorWrite(false);
  73015. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73016. renderSubMesh(depthOnlySubMeshes.data[index]);
  73017. }
  73018. engine.setColorWrite(true);
  73019. }
  73020. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73021. renderSubMesh(opaqueSubMeshes.data[index]);
  73022. }
  73023. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73024. renderSubMesh(alphaTestSubMeshes.data[index]);
  73025. }
  73026. if (transparentSubMeshes.length) {
  73027. // Sort sub meshes
  73028. for (index = 0; index < transparentSubMeshes.length; index++) {
  73029. var submesh = transparentSubMeshes.data[index];
  73030. var boundingInfo = submesh.getBoundingInfo();
  73031. if (boundingInfo && scene.activeCamera) {
  73032. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  73033. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  73034. }
  73035. }
  73036. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  73037. sortedArray.sort(function (a, b) {
  73038. // Alpha index first
  73039. if (a._alphaIndex > b._alphaIndex) {
  73040. return 1;
  73041. }
  73042. if (a._alphaIndex < b._alphaIndex) {
  73043. return -1;
  73044. }
  73045. // Then distance to camera
  73046. if (a._distanceToCamera < b._distanceToCamera) {
  73047. return 1;
  73048. }
  73049. if (a._distanceToCamera > b._distanceToCamera) {
  73050. return -1;
  73051. }
  73052. return 0;
  73053. });
  73054. // Render sub meshes
  73055. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  73056. for (index = 0; index < sortedArray.length; index++) {
  73057. renderSubMesh(sortedArray[index]);
  73058. }
  73059. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73060. }
  73061. };
  73062. };
  73063. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  73064. var transform = scene.getTransformMatrix();
  73065. var meshPosition;
  73066. if (this.useCustomMeshPosition) {
  73067. meshPosition = this.customMeshPosition;
  73068. }
  73069. else if (this.attachedNode) {
  73070. meshPosition = this.attachedNode.position;
  73071. }
  73072. else {
  73073. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  73074. }
  73075. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  73076. this._screenCoordinates.x = pos.x / this._viewPort.width;
  73077. this._screenCoordinates.y = pos.y / this._viewPort.height;
  73078. if (this.invert)
  73079. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  73080. };
  73081. // Static methods
  73082. /**
  73083. * Creates a default mesh for the Volumeric Light Scattering post-process
  73084. * @param {string} The mesh name
  73085. * @param {BABYLON.Scene} The scene where to create the mesh
  73086. * @return {BABYLON.Mesh} the default mesh
  73087. */
  73088. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  73089. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  73090. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  73091. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  73092. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  73093. mesh.material = material;
  73094. return mesh;
  73095. };
  73096. __decorate([
  73097. BABYLON.serializeAsVector3()
  73098. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  73099. __decorate([
  73100. BABYLON.serialize()
  73101. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  73102. __decorate([
  73103. BABYLON.serialize()
  73104. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  73105. __decorate([
  73106. BABYLON.serializeAsMeshReference()
  73107. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  73108. __decorate([
  73109. BABYLON.serialize()
  73110. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  73111. __decorate([
  73112. BABYLON.serialize()
  73113. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  73114. __decorate([
  73115. BABYLON.serialize()
  73116. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  73117. __decorate([
  73118. BABYLON.serialize()
  73119. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  73120. __decorate([
  73121. BABYLON.serialize()
  73122. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  73123. return VolumetricLightScatteringPostProcess;
  73124. }(BABYLON.PostProcess));
  73125. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  73126. })(BABYLON || (BABYLON = {}));
  73127. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  73128. "use strict";
  73129. //
  73130. // This post-process allows the modification of rendered colors by using
  73131. // a 'look-up table' (LUT). This effect is also called Color Grading.
  73132. //
  73133. // The object needs to be provided an url to a texture containing the color
  73134. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  73135. // Use an image editing software to tweak the LUT to match your needs.
  73136. //
  73137. // For an example of a color LUT, see here:
  73138. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  73139. // For explanations on color grading, see here:
  73140. // http://udn.epicgames.com/Three/ColorGrading.html
  73141. //
  73142. var BABYLON;
  73143. (function (BABYLON) {
  73144. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  73145. __extends(ColorCorrectionPostProcess, _super);
  73146. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  73147. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  73148. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73149. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  73150. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73151. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73152. _this.onApply = function (effect) {
  73153. effect.setTexture("colorTable", _this._colorTableTexture);
  73154. };
  73155. return _this;
  73156. }
  73157. return ColorCorrectionPostProcess;
  73158. }(BABYLON.PostProcess));
  73159. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  73160. })(BABYLON || (BABYLON = {}));
  73161. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  73162. "use strict";
  73163. var BABYLON;
  73164. (function (BABYLON) {
  73165. var TonemappingOperator;
  73166. (function (TonemappingOperator) {
  73167. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  73168. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  73169. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  73170. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  73171. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  73172. ;
  73173. var TonemapPostProcess = /** @class */ (function (_super) {
  73174. __extends(TonemapPostProcess, _super);
  73175. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  73176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73177. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73178. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  73179. _this._operator = _operator;
  73180. _this.exposureAdjustment = exposureAdjustment;
  73181. var defines = "#define ";
  73182. if (_this._operator === TonemappingOperator.Hable)
  73183. defines += "HABLE_TONEMAPPING";
  73184. else if (_this._operator === TonemappingOperator.Reinhard)
  73185. defines += "REINHARD_TONEMAPPING";
  73186. else if (_this._operator === TonemappingOperator.HejiDawson)
  73187. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  73188. else if (_this._operator === TonemappingOperator.Photographic)
  73189. defines += "PHOTOGRAPHIC_TONEMAPPING";
  73190. //sadly a second call to create the effect.
  73191. _this.updateEffect(defines);
  73192. _this.onApply = function (effect) {
  73193. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  73194. };
  73195. return _this;
  73196. }
  73197. return TonemapPostProcess;
  73198. }(BABYLON.PostProcess));
  73199. BABYLON.TonemapPostProcess = TonemapPostProcess;
  73200. })(BABYLON || (BABYLON = {}));
  73201. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  73202. "use strict";
  73203. var BABYLON;
  73204. (function (BABYLON) {
  73205. var DisplayPassPostProcess = /** @class */ (function (_super) {
  73206. __extends(DisplayPassPostProcess, _super);
  73207. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  73208. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  73209. }
  73210. return DisplayPassPostProcess;
  73211. }(BABYLON.PostProcess));
  73212. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  73213. })(BABYLON || (BABYLON = {}));
  73214. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  73215. "use strict";
  73216. var BABYLON;
  73217. (function (BABYLON) {
  73218. var HighlightsPostProcess = /** @class */ (function (_super) {
  73219. __extends(HighlightsPostProcess, _super);
  73220. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73221. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73222. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  73223. }
  73224. return HighlightsPostProcess;
  73225. }(BABYLON.PostProcess));
  73226. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  73227. })(BABYLON || (BABYLON = {}));
  73228. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  73229. "use strict";
  73230. var BABYLON;
  73231. (function (BABYLON) {
  73232. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  73233. __extends(ImageProcessingPostProcess, _super);
  73234. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  73235. if (camera === void 0) { camera = null; }
  73236. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73237. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  73238. _this._fromLinearSpace = true;
  73239. /**
  73240. * Defines cache preventing GC.
  73241. */
  73242. _this._defines = {
  73243. IMAGEPROCESSING: false,
  73244. VIGNETTE: false,
  73245. VIGNETTEBLENDMODEMULTIPLY: false,
  73246. VIGNETTEBLENDMODEOPAQUE: false,
  73247. TONEMAPPING: false,
  73248. CONTRAST: false,
  73249. COLORCURVES: false,
  73250. COLORGRADING: false,
  73251. COLORGRADING3D: false,
  73252. FROMLINEARSPACE: false,
  73253. SAMPLER3DGREENDEPTH: false,
  73254. SAMPLER3DBGRMAP: false,
  73255. IMAGEPROCESSINGPOSTPROCESS: false,
  73256. EXPOSURE: false,
  73257. };
  73258. // Setup the configuration as forced by the constructor. This would then not force the
  73259. // scene materials output in linear space and let untouched the default forward pass.
  73260. if (imageProcessingConfiguration) {
  73261. imageProcessingConfiguration.applyByPostProcess = true;
  73262. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  73263. // This will cause the shader to be compiled
  73264. _this.fromLinearSpace = false;
  73265. }
  73266. else {
  73267. _this._attachImageProcessingConfiguration(null, true);
  73268. _this.imageProcessingConfiguration.applyByPostProcess = true;
  73269. }
  73270. _this.onApply = function (effect) {
  73271. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  73272. };
  73273. return _this;
  73274. }
  73275. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  73276. /**
  73277. * Gets the image processing configuration used either in this material.
  73278. */
  73279. get: function () {
  73280. return this._imageProcessingConfiguration;
  73281. },
  73282. /**
  73283. * Sets the Default image processing configuration used either in the this material.
  73284. *
  73285. * If sets to null, the scene one is in use.
  73286. */
  73287. set: function (value) {
  73288. this._attachImageProcessingConfiguration(value);
  73289. },
  73290. enumerable: true,
  73291. configurable: true
  73292. });
  73293. /**
  73294. * Attaches a new image processing configuration to the PBR Material.
  73295. * @param configuration
  73296. */
  73297. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  73298. var _this = this;
  73299. if (doNotBuild === void 0) { doNotBuild = false; }
  73300. if (configuration === this._imageProcessingConfiguration) {
  73301. return;
  73302. }
  73303. // Detaches observer.
  73304. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  73305. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  73306. }
  73307. // Pick the scene configuration if needed.
  73308. if (!configuration) {
  73309. var scene = null;
  73310. var engine = this.getEngine();
  73311. var camera = this.getCamera();
  73312. if (camera) {
  73313. scene = camera.getScene();
  73314. }
  73315. else if (engine && engine.scenes) {
  73316. var scenes = engine.scenes;
  73317. scene = scenes[scenes.length - 1];
  73318. }
  73319. else {
  73320. scene = BABYLON.Engine.LastCreatedScene;
  73321. }
  73322. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  73323. }
  73324. else {
  73325. this._imageProcessingConfiguration = configuration;
  73326. }
  73327. // Attaches observer.
  73328. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  73329. _this._updateParameters();
  73330. });
  73331. // Ensure the effect will be rebuilt.
  73332. if (!doNotBuild) {
  73333. this._updateParameters();
  73334. }
  73335. };
  73336. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  73337. /**
  73338. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  73339. */
  73340. get: function () {
  73341. return this.imageProcessingConfiguration.colorCurves;
  73342. },
  73343. /**
  73344. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  73345. */
  73346. set: function (value) {
  73347. this.imageProcessingConfiguration.colorCurves = value;
  73348. },
  73349. enumerable: true,
  73350. configurable: true
  73351. });
  73352. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  73353. /**
  73354. * Gets wether the color curves effect is enabled.
  73355. */
  73356. get: function () {
  73357. return this.imageProcessingConfiguration.colorCurvesEnabled;
  73358. },
  73359. /**
  73360. * Sets wether the color curves effect is enabled.
  73361. */
  73362. set: function (value) {
  73363. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  73364. },
  73365. enumerable: true,
  73366. configurable: true
  73367. });
  73368. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  73369. /**
  73370. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  73371. */
  73372. get: function () {
  73373. return this.imageProcessingConfiguration.colorGradingTexture;
  73374. },
  73375. /**
  73376. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  73377. */
  73378. set: function (value) {
  73379. this.imageProcessingConfiguration.colorGradingTexture = value;
  73380. },
  73381. enumerable: true,
  73382. configurable: true
  73383. });
  73384. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  73385. /**
  73386. * Gets wether the color grading effect is enabled.
  73387. */
  73388. get: function () {
  73389. return this.imageProcessingConfiguration.colorGradingEnabled;
  73390. },
  73391. /**
  73392. * Gets wether the color grading effect is enabled.
  73393. */
  73394. set: function (value) {
  73395. this.imageProcessingConfiguration.colorGradingEnabled = value;
  73396. },
  73397. enumerable: true,
  73398. configurable: true
  73399. });
  73400. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  73401. /**
  73402. * Gets exposure used in the effect.
  73403. */
  73404. get: function () {
  73405. return this.imageProcessingConfiguration.exposure;
  73406. },
  73407. /**
  73408. * Sets exposure used in the effect.
  73409. */
  73410. set: function (value) {
  73411. this.imageProcessingConfiguration.exposure = value;
  73412. },
  73413. enumerable: true,
  73414. configurable: true
  73415. });
  73416. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  73417. /**
  73418. * Gets wether tonemapping is enabled or not.
  73419. */
  73420. get: function () {
  73421. return this._imageProcessingConfiguration.toneMappingEnabled;
  73422. },
  73423. /**
  73424. * Sets wether tonemapping is enabled or not
  73425. */
  73426. set: function (value) {
  73427. this._imageProcessingConfiguration.toneMappingEnabled = value;
  73428. },
  73429. enumerable: true,
  73430. configurable: true
  73431. });
  73432. ;
  73433. ;
  73434. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  73435. /**
  73436. * Gets contrast used in the effect.
  73437. */
  73438. get: function () {
  73439. return this.imageProcessingConfiguration.contrast;
  73440. },
  73441. /**
  73442. * Sets contrast used in the effect.
  73443. */
  73444. set: function (value) {
  73445. this.imageProcessingConfiguration.contrast = value;
  73446. },
  73447. enumerable: true,
  73448. configurable: true
  73449. });
  73450. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  73451. /**
  73452. * Gets Vignette stretch size.
  73453. */
  73454. get: function () {
  73455. return this.imageProcessingConfiguration.vignetteStretch;
  73456. },
  73457. /**
  73458. * Sets Vignette stretch size.
  73459. */
  73460. set: function (value) {
  73461. this.imageProcessingConfiguration.vignetteStretch = value;
  73462. },
  73463. enumerable: true,
  73464. configurable: true
  73465. });
  73466. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  73467. /**
  73468. * Gets Vignette centre X Offset.
  73469. */
  73470. get: function () {
  73471. return this.imageProcessingConfiguration.vignetteCentreX;
  73472. },
  73473. /**
  73474. * Sets Vignette centre X Offset.
  73475. */
  73476. set: function (value) {
  73477. this.imageProcessingConfiguration.vignetteCentreX = value;
  73478. },
  73479. enumerable: true,
  73480. configurable: true
  73481. });
  73482. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  73483. /**
  73484. * Gets Vignette centre Y Offset.
  73485. */
  73486. get: function () {
  73487. return this.imageProcessingConfiguration.vignetteCentreY;
  73488. },
  73489. /**
  73490. * Sets Vignette centre Y Offset.
  73491. */
  73492. set: function (value) {
  73493. this.imageProcessingConfiguration.vignetteCentreY = value;
  73494. },
  73495. enumerable: true,
  73496. configurable: true
  73497. });
  73498. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  73499. /**
  73500. * Gets Vignette weight or intensity of the vignette effect.
  73501. */
  73502. get: function () {
  73503. return this.imageProcessingConfiguration.vignetteWeight;
  73504. },
  73505. /**
  73506. * Sets Vignette weight or intensity of the vignette effect.
  73507. */
  73508. set: function (value) {
  73509. this.imageProcessingConfiguration.vignetteWeight = value;
  73510. },
  73511. enumerable: true,
  73512. configurable: true
  73513. });
  73514. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  73515. /**
  73516. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  73517. * if vignetteEnabled is set to true.
  73518. */
  73519. get: function () {
  73520. return this.imageProcessingConfiguration.vignetteColor;
  73521. },
  73522. /**
  73523. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  73524. * if vignetteEnabled is set to true.
  73525. */
  73526. set: function (value) {
  73527. this.imageProcessingConfiguration.vignetteColor = value;
  73528. },
  73529. enumerable: true,
  73530. configurable: true
  73531. });
  73532. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  73533. /**
  73534. * Gets Camera field of view used by the Vignette effect.
  73535. */
  73536. get: function () {
  73537. return this.imageProcessingConfiguration.vignetteCameraFov;
  73538. },
  73539. /**
  73540. * Sets Camera field of view used by the Vignette effect.
  73541. */
  73542. set: function (value) {
  73543. this.imageProcessingConfiguration.vignetteCameraFov = value;
  73544. },
  73545. enumerable: true,
  73546. configurable: true
  73547. });
  73548. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  73549. /**
  73550. * Gets the vignette blend mode allowing different kind of effect.
  73551. */
  73552. get: function () {
  73553. return this.imageProcessingConfiguration.vignetteBlendMode;
  73554. },
  73555. /**
  73556. * Sets the vignette blend mode allowing different kind of effect.
  73557. */
  73558. set: function (value) {
  73559. this.imageProcessingConfiguration.vignetteBlendMode = value;
  73560. },
  73561. enumerable: true,
  73562. configurable: true
  73563. });
  73564. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  73565. /**
  73566. * Gets wether the vignette effect is enabled.
  73567. */
  73568. get: function () {
  73569. return this.imageProcessingConfiguration.vignetteEnabled;
  73570. },
  73571. /**
  73572. * Sets wether the vignette effect is enabled.
  73573. */
  73574. set: function (value) {
  73575. this.imageProcessingConfiguration.vignetteEnabled = value;
  73576. },
  73577. enumerable: true,
  73578. configurable: true
  73579. });
  73580. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  73581. /**
  73582. * Gets wether the input of the processing is in Gamma or Linear Space.
  73583. */
  73584. get: function () {
  73585. return this._fromLinearSpace;
  73586. },
  73587. /**
  73588. * Sets wether the input of the processing is in Gamma or Linear Space.
  73589. */
  73590. set: function (value) {
  73591. if (this._fromLinearSpace === value) {
  73592. return;
  73593. }
  73594. this._fromLinearSpace = value;
  73595. this._updateParameters();
  73596. },
  73597. enumerable: true,
  73598. configurable: true
  73599. });
  73600. ImageProcessingPostProcess.prototype.getClassName = function () {
  73601. return "ImageProcessingPostProcess";
  73602. };
  73603. ImageProcessingPostProcess.prototype._updateParameters = function () {
  73604. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  73605. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  73606. var defines = "";
  73607. for (var define in this._defines) {
  73608. if (this._defines[define]) {
  73609. defines += "#define " + define + ";\r\n";
  73610. }
  73611. }
  73612. var samplers = ["textureSampler"];
  73613. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  73614. var uniforms = ["scale"];
  73615. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  73616. this.updateEffect(defines, uniforms, samplers);
  73617. };
  73618. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  73619. _super.prototype.dispose.call(this, camera);
  73620. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  73621. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  73622. }
  73623. this.imageProcessingConfiguration.applyByPostProcess = false;
  73624. };
  73625. __decorate([
  73626. BABYLON.serialize()
  73627. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  73628. return ImageProcessingPostProcess;
  73629. }(BABYLON.PostProcess));
  73630. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  73631. })(BABYLON || (BABYLON = {}));
  73632. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  73633. "use strict";
  73634. var BABYLON;
  73635. (function (BABYLON) {
  73636. var Bone = /** @class */ (function (_super) {
  73637. __extends(Bone, _super);
  73638. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  73639. if (parentBone === void 0) { parentBone = null; }
  73640. if (localMatrix === void 0) { localMatrix = null; }
  73641. if (restPose === void 0) { restPose = null; }
  73642. if (baseMatrix === void 0) { baseMatrix = null; }
  73643. if (index === void 0) { index = null; }
  73644. var _this = _super.call(this, name, skeleton.getScene()) || this;
  73645. _this.name = name;
  73646. _this.children = new Array();
  73647. _this.animations = new Array();
  73648. // Set this value to map this bone to a different index in the transform matrices.
  73649. // Set this value to -1 to exclude the bone from the transform matrices.
  73650. _this._index = null;
  73651. _this._worldTransform = new BABYLON.Matrix();
  73652. _this._absoluteTransform = new BABYLON.Matrix();
  73653. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  73654. _this._scaleMatrix = BABYLON.Matrix.Identity();
  73655. _this._scaleVector = BABYLON.Vector3.One();
  73656. _this._negateScaleChildren = BABYLON.Vector3.One();
  73657. _this._scalingDeterminant = 1;
  73658. _this._skeleton = skeleton;
  73659. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  73660. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  73661. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  73662. _this._index = index;
  73663. skeleton.bones.push(_this);
  73664. _this.setParent(parentBone, false);
  73665. _this._updateDifferenceMatrix();
  73666. return _this;
  73667. }
  73668. Object.defineProperty(Bone.prototype, "_matrix", {
  73669. get: function () {
  73670. return this._localMatrix;
  73671. },
  73672. set: function (val) {
  73673. if (this._localMatrix) {
  73674. this._localMatrix.copyFrom(val);
  73675. }
  73676. else {
  73677. this._localMatrix = val;
  73678. }
  73679. },
  73680. enumerable: true,
  73681. configurable: true
  73682. });
  73683. // Members
  73684. Bone.prototype.getSkeleton = function () {
  73685. return this._skeleton;
  73686. };
  73687. Bone.prototype.getParent = function () {
  73688. return this._parent;
  73689. };
  73690. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  73691. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  73692. if (this._parent === parent) {
  73693. return;
  73694. }
  73695. if (this._parent) {
  73696. var index = this._parent.children.indexOf(this);
  73697. if (index !== -1) {
  73698. this._parent.children.splice(index, 1);
  73699. }
  73700. }
  73701. this._parent = parent;
  73702. if (this._parent) {
  73703. this._parent.children.push(this);
  73704. }
  73705. if (updateDifferenceMatrix) {
  73706. this._updateDifferenceMatrix();
  73707. }
  73708. };
  73709. Bone.prototype.getLocalMatrix = function () {
  73710. return this._localMatrix;
  73711. };
  73712. Bone.prototype.getBaseMatrix = function () {
  73713. return this._baseMatrix;
  73714. };
  73715. Bone.prototype.getRestPose = function () {
  73716. return this._restPose;
  73717. };
  73718. Bone.prototype.returnToRest = function () {
  73719. this.updateMatrix(this._restPose.clone());
  73720. };
  73721. Bone.prototype.getWorldMatrix = function () {
  73722. return this._worldTransform;
  73723. };
  73724. Bone.prototype.getInvertedAbsoluteTransform = function () {
  73725. return this._invertedAbsoluteTransform;
  73726. };
  73727. Bone.prototype.getAbsoluteTransform = function () {
  73728. return this._absoluteTransform;
  73729. };
  73730. Object.defineProperty(Bone.prototype, "position", {
  73731. // Properties (matches AbstractMesh properties)
  73732. get: function () {
  73733. return this.getPosition();
  73734. },
  73735. set: function (newPosition) {
  73736. this.setPosition(newPosition);
  73737. },
  73738. enumerable: true,
  73739. configurable: true
  73740. });
  73741. Object.defineProperty(Bone.prototype, "rotation", {
  73742. get: function () {
  73743. return this.getRotation();
  73744. },
  73745. set: function (newRotation) {
  73746. this.setRotation(newRotation);
  73747. },
  73748. enumerable: true,
  73749. configurable: true
  73750. });
  73751. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  73752. get: function () {
  73753. return this.getRotationQuaternion();
  73754. },
  73755. set: function (newRotation) {
  73756. this.setRotationQuaternion(newRotation);
  73757. },
  73758. enumerable: true,
  73759. configurable: true
  73760. });
  73761. Object.defineProperty(Bone.prototype, "scaling", {
  73762. get: function () {
  73763. return this.getScale();
  73764. },
  73765. set: function (newScaling) {
  73766. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  73767. },
  73768. enumerable: true,
  73769. configurable: true
  73770. });
  73771. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  73772. /**
  73773. * Gets the animation properties override
  73774. */
  73775. get: function () {
  73776. return this._skeleton.animationPropertiesOverride;
  73777. },
  73778. enumerable: true,
  73779. configurable: true
  73780. });
  73781. // Methods
  73782. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  73783. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  73784. this._baseMatrix = matrix.clone();
  73785. this._localMatrix = matrix.clone();
  73786. this._skeleton._markAsDirty();
  73787. if (updateDifferenceMatrix) {
  73788. this._updateDifferenceMatrix();
  73789. }
  73790. };
  73791. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  73792. if (!rootMatrix) {
  73793. rootMatrix = this._baseMatrix;
  73794. }
  73795. if (this._parent) {
  73796. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73797. }
  73798. else {
  73799. this._absoluteTransform.copyFrom(rootMatrix);
  73800. }
  73801. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  73802. for (var index = 0; index < this.children.length; index++) {
  73803. this.children[index]._updateDifferenceMatrix();
  73804. }
  73805. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  73806. };
  73807. Bone.prototype.markAsDirty = function () {
  73808. this._currentRenderId++;
  73809. this._childRenderId++;
  73810. this._skeleton._markAsDirty();
  73811. };
  73812. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  73813. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73814. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  73815. // all animation may be coming from a library skeleton, so may need to create animation
  73816. if (this.animations.length === 0) {
  73817. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  73818. this.animations[0].setKeys([]);
  73819. }
  73820. // get animation info / verify there is such a range from the source bone
  73821. var sourceRange = source.animations[0].getRange(rangeName);
  73822. if (!sourceRange) {
  73823. return false;
  73824. }
  73825. var from = sourceRange.from;
  73826. var to = sourceRange.to;
  73827. var sourceKeys = source.animations[0].getKeys();
  73828. // rescaling prep
  73829. var sourceBoneLength = source.length;
  73830. var sourceParent = source.getParent();
  73831. var parent = this.getParent();
  73832. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  73833. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  73834. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  73835. var destKeys = this.animations[0].getKeys();
  73836. // loop vars declaration
  73837. var orig;
  73838. var origTranslation;
  73839. var mat;
  73840. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  73841. orig = sourceKeys[key];
  73842. if (orig.frame >= from && orig.frame <= to) {
  73843. if (rescaleAsRequired) {
  73844. mat = orig.value.clone();
  73845. // scale based on parent ratio, when bone has parent
  73846. if (parentScalingReqd) {
  73847. origTranslation = mat.getTranslation();
  73848. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  73849. // scale based on skeleton dimension ratio when root bone, and value is passed
  73850. }
  73851. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  73852. origTranslation = mat.getTranslation();
  73853. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  73854. // use original when root bone, and no data for skelDimensionsRatio
  73855. }
  73856. else {
  73857. mat = orig.value;
  73858. }
  73859. }
  73860. else {
  73861. mat = orig.value;
  73862. }
  73863. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  73864. }
  73865. }
  73866. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  73867. return true;
  73868. };
  73869. /**
  73870. * Translate the bone in local or world space.
  73871. * @param vec The amount to translate the bone.
  73872. * @param space The space that the translation is in.
  73873. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73874. */
  73875. Bone.prototype.translate = function (vec, space, mesh) {
  73876. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73877. var lm = this.getLocalMatrix();
  73878. if (space == BABYLON.Space.LOCAL) {
  73879. lm.m[12] += vec.x;
  73880. lm.m[13] += vec.y;
  73881. lm.m[14] += vec.z;
  73882. }
  73883. else {
  73884. var wm = null;
  73885. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73886. if (mesh) {
  73887. wm = mesh.getWorldMatrix();
  73888. }
  73889. this._skeleton.computeAbsoluteTransforms();
  73890. var tmat = Bone._tmpMats[0];
  73891. var tvec = Bone._tmpVecs[0];
  73892. if (this._parent) {
  73893. if (mesh && wm) {
  73894. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73895. tmat.multiplyToRef(wm, tmat);
  73896. }
  73897. else {
  73898. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73899. }
  73900. }
  73901. tmat.m[12] = 0;
  73902. tmat.m[13] = 0;
  73903. tmat.m[14] = 0;
  73904. tmat.invert();
  73905. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  73906. lm.m[12] += tvec.x;
  73907. lm.m[13] += tvec.y;
  73908. lm.m[14] += tvec.z;
  73909. }
  73910. this.markAsDirty();
  73911. };
  73912. /**
  73913. * Set the postion of the bone in local or world space.
  73914. * @param position The position to set the bone.
  73915. * @param space The space that the position is in.
  73916. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73917. */
  73918. Bone.prototype.setPosition = function (position, space, mesh) {
  73919. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73920. var lm = this.getLocalMatrix();
  73921. if (space == BABYLON.Space.LOCAL) {
  73922. lm.m[12] = position.x;
  73923. lm.m[13] = position.y;
  73924. lm.m[14] = position.z;
  73925. }
  73926. else {
  73927. var wm = null;
  73928. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73929. if (mesh) {
  73930. wm = mesh.getWorldMatrix();
  73931. }
  73932. this._skeleton.computeAbsoluteTransforms();
  73933. var tmat = Bone._tmpMats[0];
  73934. var vec = Bone._tmpVecs[0];
  73935. if (this._parent) {
  73936. if (mesh && wm) {
  73937. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73938. tmat.multiplyToRef(wm, tmat);
  73939. }
  73940. else {
  73941. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73942. }
  73943. }
  73944. tmat.invert();
  73945. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  73946. lm.m[12] = vec.x;
  73947. lm.m[13] = vec.y;
  73948. lm.m[14] = vec.z;
  73949. }
  73950. this.markAsDirty();
  73951. };
  73952. /**
  73953. * Set the absolute postion of the bone (world space).
  73954. * @param position The position to set the bone.
  73955. * @param mesh The mesh that this bone is attached to.
  73956. */
  73957. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  73958. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  73959. };
  73960. /**
  73961. * Set the scale of the bone on the x, y and z axes.
  73962. * @param x The scale of the bone on the x axis.
  73963. * @param x The scale of the bone on the y axis.
  73964. * @param z The scale of the bone on the z axis.
  73965. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73966. */
  73967. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  73968. if (scaleChildren === void 0) { scaleChildren = false; }
  73969. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  73970. if (!scaleChildren) {
  73971. this._negateScaleChildren.x = 1 / x;
  73972. this._negateScaleChildren.y = 1 / y;
  73973. this._negateScaleChildren.z = 1 / z;
  73974. }
  73975. this._syncScaleVector();
  73976. }
  73977. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  73978. };
  73979. /**
  73980. * Scale the bone on the x, y and z axes.
  73981. * @param x The amount to scale the bone on the x axis.
  73982. * @param x The amount to scale the bone on the y axis.
  73983. * @param z The amount to scale the bone on the z axis.
  73984. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73985. */
  73986. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  73987. if (scaleChildren === void 0) { scaleChildren = false; }
  73988. var locMat = this.getLocalMatrix();
  73989. var origLocMat = Bone._tmpMats[0];
  73990. origLocMat.copyFrom(locMat);
  73991. var origLocMatInv = Bone._tmpMats[1];
  73992. origLocMatInv.copyFrom(origLocMat);
  73993. origLocMatInv.invert();
  73994. var scaleMat = Bone._tmpMats[2];
  73995. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  73996. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  73997. this._scaleVector.x *= x;
  73998. this._scaleVector.y *= y;
  73999. this._scaleVector.z *= z;
  74000. locMat.multiplyToRef(origLocMatInv, locMat);
  74001. locMat.multiplyToRef(scaleMat, locMat);
  74002. locMat.multiplyToRef(origLocMat, locMat);
  74003. var parent = this.getParent();
  74004. if (parent) {
  74005. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  74006. }
  74007. else {
  74008. this.getAbsoluteTransform().copyFrom(locMat);
  74009. }
  74010. var len = this.children.length;
  74011. scaleMat.invert();
  74012. for (var i = 0; i < len; i++) {
  74013. var child = this.children[i];
  74014. var cm = child.getLocalMatrix();
  74015. cm.multiplyToRef(scaleMat, cm);
  74016. var lm = child.getLocalMatrix();
  74017. lm.m[12] *= x;
  74018. lm.m[13] *= y;
  74019. lm.m[14] *= z;
  74020. }
  74021. this.computeAbsoluteTransforms();
  74022. if (scaleChildren) {
  74023. for (var i = 0; i < len; i++) {
  74024. this.children[i].scale(x, y, z, scaleChildren);
  74025. }
  74026. }
  74027. this.markAsDirty();
  74028. };
  74029. /**
  74030. * Set the yaw, pitch, and roll of the bone in local or world space.
  74031. * @param yaw The rotation of the bone on the y axis.
  74032. * @param pitch The rotation of the bone on the x axis.
  74033. * @param roll The rotation of the bone on the z axis.
  74034. * @param space The space that the axes of rotation are in.
  74035. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74036. */
  74037. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  74038. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74039. var rotMat = Bone._tmpMats[0];
  74040. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  74041. var rotMatInv = Bone._tmpMats[1];
  74042. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  74043. rotMatInv.multiplyToRef(rotMat, rotMat);
  74044. this._rotateWithMatrix(rotMat, space, mesh);
  74045. };
  74046. /**
  74047. * Rotate the bone on an axis in local or world space.
  74048. * @param axis The axis to rotate the bone on.
  74049. * @param amount The amount to rotate the bone.
  74050. * @param space The space that the axis is in.
  74051. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74052. */
  74053. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  74054. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74055. var rmat = Bone._tmpMats[0];
  74056. rmat.m[12] = 0;
  74057. rmat.m[13] = 0;
  74058. rmat.m[14] = 0;
  74059. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  74060. this._rotateWithMatrix(rmat, space, mesh);
  74061. };
  74062. /**
  74063. * Set the rotation of the bone to a particular axis angle in local or world space.
  74064. * @param axis The axis to rotate the bone on.
  74065. * @param angle The angle that the bone should be rotated to.
  74066. * @param space The space that the axis is in.
  74067. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74068. */
  74069. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  74070. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74071. var rotMat = Bone._tmpMats[0];
  74072. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  74073. var rotMatInv = Bone._tmpMats[1];
  74074. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  74075. rotMatInv.multiplyToRef(rotMat, rotMat);
  74076. this._rotateWithMatrix(rotMat, space, mesh);
  74077. };
  74078. /**
  74079. * Set the euler rotation of the bone in local of world space.
  74080. * @param rotation The euler rotation that the bone should be set to.
  74081. * @param space The space that the rotation is in.
  74082. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74083. */
  74084. Bone.prototype.setRotation = function (rotation, space, mesh) {
  74085. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74086. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  74087. };
  74088. /**
  74089. * Set the quaternion rotation of the bone in local of world space.
  74090. * @param quat The quaternion rotation that the bone should be set to.
  74091. * @param space The space that the rotation is in.
  74092. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74093. */
  74094. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  74095. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74096. var rotMatInv = Bone._tmpMats[0];
  74097. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  74098. var rotMat = Bone._tmpMats[1];
  74099. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  74100. rotMatInv.multiplyToRef(rotMat, rotMat);
  74101. this._rotateWithMatrix(rotMat, space, mesh);
  74102. };
  74103. /**
  74104. * Set the rotation matrix of the bone in local of world space.
  74105. * @param rotMat The rotation matrix that the bone should be set to.
  74106. * @param space The space that the rotation is in.
  74107. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74108. */
  74109. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  74110. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74111. var rotMatInv = Bone._tmpMats[0];
  74112. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  74113. var rotMat2 = Bone._tmpMats[1];
  74114. rotMat2.copyFrom(rotMat);
  74115. rotMatInv.multiplyToRef(rotMat, rotMat2);
  74116. this._rotateWithMatrix(rotMat2, space, mesh);
  74117. };
  74118. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  74119. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74120. var lmat = this.getLocalMatrix();
  74121. var lx = lmat.m[12];
  74122. var ly = lmat.m[13];
  74123. var lz = lmat.m[14];
  74124. var parent = this.getParent();
  74125. var parentScale = Bone._tmpMats[3];
  74126. var parentScaleInv = Bone._tmpMats[4];
  74127. if (parent) {
  74128. if (space == BABYLON.Space.WORLD) {
  74129. if (mesh) {
  74130. parentScale.copyFrom(mesh.getWorldMatrix());
  74131. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  74132. }
  74133. else {
  74134. parentScale.copyFrom(parent.getAbsoluteTransform());
  74135. }
  74136. }
  74137. else {
  74138. parentScale = parent._scaleMatrix;
  74139. }
  74140. parentScaleInv.copyFrom(parentScale);
  74141. parentScaleInv.invert();
  74142. lmat.multiplyToRef(parentScale, lmat);
  74143. lmat.multiplyToRef(rmat, lmat);
  74144. lmat.multiplyToRef(parentScaleInv, lmat);
  74145. }
  74146. else {
  74147. if (space == BABYLON.Space.WORLD && mesh) {
  74148. parentScale.copyFrom(mesh.getWorldMatrix());
  74149. parentScaleInv.copyFrom(parentScale);
  74150. parentScaleInv.invert();
  74151. lmat.multiplyToRef(parentScale, lmat);
  74152. lmat.multiplyToRef(rmat, lmat);
  74153. lmat.multiplyToRef(parentScaleInv, lmat);
  74154. }
  74155. else {
  74156. lmat.multiplyToRef(rmat, lmat);
  74157. }
  74158. }
  74159. lmat.m[12] = lx;
  74160. lmat.m[13] = ly;
  74161. lmat.m[14] = lz;
  74162. this.computeAbsoluteTransforms();
  74163. this.markAsDirty();
  74164. };
  74165. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  74166. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74167. if (space == BABYLON.Space.WORLD) {
  74168. var scaleMatrix = Bone._tmpMats[2];
  74169. scaleMatrix.copyFrom(this._scaleMatrix);
  74170. rotMatInv.copyFrom(this.getAbsoluteTransform());
  74171. if (mesh) {
  74172. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  74173. var meshScale = Bone._tmpMats[3];
  74174. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  74175. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  74176. }
  74177. rotMatInv.invert();
  74178. scaleMatrix.m[0] *= this._scalingDeterminant;
  74179. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  74180. }
  74181. else {
  74182. rotMatInv.copyFrom(this.getLocalMatrix());
  74183. rotMatInv.invert();
  74184. var scaleMatrix = Bone._tmpMats[2];
  74185. scaleMatrix.copyFrom(this._scaleMatrix);
  74186. if (this._parent) {
  74187. var pscaleMatrix = Bone._tmpMats[3];
  74188. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  74189. pscaleMatrix.invert();
  74190. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  74191. }
  74192. else {
  74193. scaleMatrix.m[0] *= this._scalingDeterminant;
  74194. }
  74195. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  74196. }
  74197. };
  74198. /**
  74199. * Get the scale of the bone
  74200. * @returns the scale of the bone
  74201. */
  74202. Bone.prototype.getScale = function () {
  74203. return this._scaleVector.clone();
  74204. };
  74205. /**
  74206. * Copy the scale of the bone to a vector3.
  74207. * @param result The vector3 to copy the scale to
  74208. */
  74209. Bone.prototype.getScaleToRef = function (result) {
  74210. result.copyFrom(this._scaleVector);
  74211. };
  74212. /**
  74213. * Get the position of the bone in local or world space.
  74214. * @param space The space that the returned position is in.
  74215. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74216. * @returns The position of the bone
  74217. */
  74218. Bone.prototype.getPosition = function (space, mesh) {
  74219. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74220. if (mesh === void 0) { mesh = null; }
  74221. var pos = BABYLON.Vector3.Zero();
  74222. this.getPositionToRef(space, mesh, pos);
  74223. return pos;
  74224. };
  74225. /**
  74226. * Copy the position of the bone to a vector3 in local or world space.
  74227. * @param space The space that the returned position is in.
  74228. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74229. * @param result The vector3 to copy the position to.
  74230. */
  74231. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  74232. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74233. if (space == BABYLON.Space.LOCAL) {
  74234. var lm = this.getLocalMatrix();
  74235. result.x = lm.m[12];
  74236. result.y = lm.m[13];
  74237. result.z = lm.m[14];
  74238. }
  74239. else {
  74240. var wm = null;
  74241. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  74242. if (mesh) {
  74243. wm = mesh.getWorldMatrix();
  74244. }
  74245. this._skeleton.computeAbsoluteTransforms();
  74246. var tmat = Bone._tmpMats[0];
  74247. if (mesh && wm) {
  74248. tmat.copyFrom(this.getAbsoluteTransform());
  74249. tmat.multiplyToRef(wm, tmat);
  74250. }
  74251. else {
  74252. tmat = this.getAbsoluteTransform();
  74253. }
  74254. result.x = tmat.m[12];
  74255. result.y = tmat.m[13];
  74256. result.z = tmat.m[14];
  74257. }
  74258. };
  74259. /**
  74260. * Get the absolute position of the bone (world space).
  74261. * @param mesh The mesh that this bone is attached to.
  74262. * @returns The absolute position of the bone
  74263. */
  74264. Bone.prototype.getAbsolutePosition = function (mesh) {
  74265. if (mesh === void 0) { mesh = null; }
  74266. var pos = BABYLON.Vector3.Zero();
  74267. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  74268. return pos;
  74269. };
  74270. /**
  74271. * Copy the absolute position of the bone (world space) to the result param.
  74272. * @param mesh The mesh that this bone is attached to.
  74273. * @param result The vector3 to copy the absolute position to.
  74274. */
  74275. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  74276. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  74277. };
  74278. /**
  74279. * Compute the absolute transforms of this bone and its children.
  74280. */
  74281. Bone.prototype.computeAbsoluteTransforms = function () {
  74282. if (this._parent) {
  74283. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  74284. }
  74285. else {
  74286. this._absoluteTransform.copyFrom(this._localMatrix);
  74287. var poseMatrix = this._skeleton.getPoseMatrix();
  74288. if (poseMatrix) {
  74289. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  74290. }
  74291. }
  74292. var children = this.children;
  74293. var len = children.length;
  74294. for (var i = 0; i < len; i++) {
  74295. children[i].computeAbsoluteTransforms();
  74296. }
  74297. };
  74298. Bone.prototype._syncScaleVector = function () {
  74299. var lm = this.getLocalMatrix();
  74300. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  74301. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  74302. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  74303. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  74304. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  74305. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  74306. this._scaleVector.x = xs * Math.sqrt(xsq);
  74307. this._scaleVector.y = ys * Math.sqrt(ysq);
  74308. this._scaleVector.z = zs * Math.sqrt(zsq);
  74309. if (this._parent) {
  74310. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  74311. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  74312. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  74313. }
  74314. 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);
  74315. };
  74316. /**
  74317. * Get the world direction from an axis that is in the local space of the bone.
  74318. * @param localAxis The local direction that is used to compute the world direction.
  74319. * @param mesh The mesh that this bone is attached to.
  74320. * @returns The world direction
  74321. */
  74322. Bone.prototype.getDirection = function (localAxis, mesh) {
  74323. if (mesh === void 0) { mesh = null; }
  74324. var result = BABYLON.Vector3.Zero();
  74325. this.getDirectionToRef(localAxis, mesh, result);
  74326. return result;
  74327. };
  74328. /**
  74329. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  74330. * @param localAxis The local direction that is used to compute the world direction.
  74331. * @param mesh The mesh that this bone is attached to.
  74332. * @param result The vector3 that the world direction will be copied to.
  74333. */
  74334. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  74335. if (mesh === void 0) { mesh = null; }
  74336. var wm = null;
  74337. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  74338. if (mesh) {
  74339. wm = mesh.getWorldMatrix();
  74340. }
  74341. this._skeleton.computeAbsoluteTransforms();
  74342. var mat = Bone._tmpMats[0];
  74343. mat.copyFrom(this.getAbsoluteTransform());
  74344. if (mesh && wm) {
  74345. mat.multiplyToRef(wm, mat);
  74346. }
  74347. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  74348. result.normalize();
  74349. };
  74350. /**
  74351. * Get the euler rotation of the bone in local or world space.
  74352. * @param space The space that the rotation should be in.
  74353. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74354. * @returns The euler rotation
  74355. */
  74356. Bone.prototype.getRotation = function (space, mesh) {
  74357. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74358. if (mesh === void 0) { mesh = null; }
  74359. var result = BABYLON.Vector3.Zero();
  74360. this.getRotationToRef(space, mesh, result);
  74361. return result;
  74362. };
  74363. /**
  74364. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  74365. * @param space The space that the rotation should be in.
  74366. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74367. * @param result The vector3 that the rotation should be copied to.
  74368. */
  74369. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  74370. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74371. if (mesh === void 0) { mesh = null; }
  74372. var quat = Bone._tmpQuat;
  74373. this.getRotationQuaternionToRef(space, mesh, quat);
  74374. quat.toEulerAnglesToRef(result);
  74375. };
  74376. /**
  74377. * Get the quaternion rotation of the bone in either local or world space.
  74378. * @param space The space that the rotation should be in.
  74379. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74380. * @returns The quaternion rotation
  74381. */
  74382. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  74383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74384. if (mesh === void 0) { mesh = null; }
  74385. var result = BABYLON.Quaternion.Identity();
  74386. this.getRotationQuaternionToRef(space, mesh, result);
  74387. return result;
  74388. };
  74389. /**
  74390. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  74391. * @param space The space that the rotation should be in.
  74392. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74393. * @param result The quaternion that the rotation should be copied to.
  74394. */
  74395. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  74396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74397. if (mesh === void 0) { mesh = null; }
  74398. if (space == BABYLON.Space.LOCAL) {
  74399. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  74400. }
  74401. else {
  74402. var mat = Bone._tmpMats[0];
  74403. var amat = this.getAbsoluteTransform();
  74404. if (mesh) {
  74405. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  74406. }
  74407. else {
  74408. mat.copyFrom(amat);
  74409. }
  74410. mat.m[0] *= this._scalingDeterminant;
  74411. mat.m[1] *= this._scalingDeterminant;
  74412. mat.m[2] *= this._scalingDeterminant;
  74413. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  74414. }
  74415. };
  74416. /**
  74417. * Get the rotation matrix of the bone in local or world space.
  74418. * @param space The space that the rotation should be in.
  74419. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74420. * @returns The rotation matrix
  74421. */
  74422. Bone.prototype.getRotationMatrix = function (space, mesh) {
  74423. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74424. var result = BABYLON.Matrix.Identity();
  74425. this.getRotationMatrixToRef(space, mesh, result);
  74426. return result;
  74427. };
  74428. /**
  74429. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  74430. * @param space The space that the rotation should be in.
  74431. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74432. * @param result The quaternion that the rotation should be copied to.
  74433. */
  74434. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  74435. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74436. if (space == BABYLON.Space.LOCAL) {
  74437. this.getLocalMatrix().getRotationMatrixToRef(result);
  74438. }
  74439. else {
  74440. var mat = Bone._tmpMats[0];
  74441. var amat = this.getAbsoluteTransform();
  74442. if (mesh) {
  74443. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  74444. }
  74445. else {
  74446. mat.copyFrom(amat);
  74447. }
  74448. mat.m[0] *= this._scalingDeterminant;
  74449. mat.m[1] *= this._scalingDeterminant;
  74450. mat.m[2] *= this._scalingDeterminant;
  74451. mat.getRotationMatrixToRef(result);
  74452. }
  74453. };
  74454. /**
  74455. * Get the world position of a point that is in the local space of the bone.
  74456. * @param position The local position
  74457. * @param mesh The mesh that this bone is attached to.
  74458. * @returns The world position
  74459. */
  74460. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  74461. if (mesh === void 0) { mesh = null; }
  74462. var result = BABYLON.Vector3.Zero();
  74463. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  74464. return result;
  74465. };
  74466. /**
  74467. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  74468. * @param position The local position
  74469. * @param mesh The mesh that this bone is attached to.
  74470. * @param result The vector3 that the world position should be copied to.
  74471. */
  74472. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  74473. if (mesh === void 0) { mesh = null; }
  74474. var wm = null;
  74475. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  74476. if (mesh) {
  74477. wm = mesh.getWorldMatrix();
  74478. }
  74479. this._skeleton.computeAbsoluteTransforms();
  74480. var tmat = Bone._tmpMats[0];
  74481. if (mesh && wm) {
  74482. tmat.copyFrom(this.getAbsoluteTransform());
  74483. tmat.multiplyToRef(wm, tmat);
  74484. }
  74485. else {
  74486. tmat = this.getAbsoluteTransform();
  74487. }
  74488. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  74489. };
  74490. /**
  74491. * Get the local position of a point that is in world space.
  74492. * @param position The world position
  74493. * @param mesh The mesh that this bone is attached to.
  74494. * @returns The local position
  74495. */
  74496. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  74497. if (mesh === void 0) { mesh = null; }
  74498. var result = BABYLON.Vector3.Zero();
  74499. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  74500. return result;
  74501. };
  74502. /**
  74503. * Get the local position of a point that is in world space and copy it to the result param.
  74504. * @param position The world position
  74505. * @param mesh The mesh that this bone is attached to.
  74506. * @param result The vector3 that the local position should be copied to.
  74507. */
  74508. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  74509. if (mesh === void 0) { mesh = null; }
  74510. var wm = null;
  74511. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  74512. if (mesh) {
  74513. wm = mesh.getWorldMatrix();
  74514. }
  74515. this._skeleton.computeAbsoluteTransforms();
  74516. var tmat = Bone._tmpMats[0];
  74517. tmat.copyFrom(this.getAbsoluteTransform());
  74518. if (mesh && wm) {
  74519. tmat.multiplyToRef(wm, tmat);
  74520. }
  74521. tmat.invert();
  74522. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  74523. };
  74524. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74525. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  74526. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74527. return Bone;
  74528. }(BABYLON.Node));
  74529. BABYLON.Bone = Bone;
  74530. })(BABYLON || (BABYLON = {}));
  74531. //# sourceMappingURL=babylon.bone.js.map
  74532. "use strict";
  74533. var BABYLON;
  74534. (function (BABYLON) {
  74535. var BoneIKController = /** @class */ (function () {
  74536. function BoneIKController(mesh, bone, options) {
  74537. this.targetPosition = BABYLON.Vector3.Zero();
  74538. this.poleTargetPosition = BABYLON.Vector3.Zero();
  74539. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  74540. this.poleAngle = 0;
  74541. this.slerpAmount = 1;
  74542. this._bone1Quat = BABYLON.Quaternion.Identity();
  74543. this._bone1Mat = BABYLON.Matrix.Identity();
  74544. this._bone2Ang = Math.PI;
  74545. this._maxAngle = Math.PI;
  74546. this._rightHandedSystem = false;
  74547. this._bendAxis = BABYLON.Vector3.Right();
  74548. this._slerping = false;
  74549. this._adjustRoll = 0;
  74550. this._bone2 = bone;
  74551. this._bone1 = bone.getParent();
  74552. if (!this._bone1) {
  74553. return;
  74554. }
  74555. this.mesh = mesh;
  74556. var bonePos = bone.getPosition();
  74557. if (bone.getAbsoluteTransform().determinant() > 0) {
  74558. this._rightHandedSystem = true;
  74559. this._bendAxis.x = 0;
  74560. this._bendAxis.y = 0;
  74561. this._bendAxis.z = -1;
  74562. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  74563. this._adjustRoll = Math.PI * .5;
  74564. this._bendAxis.z = 1;
  74565. }
  74566. }
  74567. if (this._bone1.length) {
  74568. var boneScale1 = this._bone1.getScale();
  74569. var boneScale2 = this._bone2.getScale();
  74570. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  74571. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  74572. }
  74573. else if (this._bone1.children[0]) {
  74574. mesh.computeWorldMatrix(true);
  74575. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  74576. var pos2 = this._bone2.getAbsolutePosition(mesh);
  74577. var pos3 = this._bone1.getAbsolutePosition(mesh);
  74578. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  74579. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  74580. }
  74581. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  74582. this.maxAngle = Math.PI;
  74583. if (options) {
  74584. if (options.targetMesh) {
  74585. this.targetMesh = options.targetMesh;
  74586. this.targetMesh.computeWorldMatrix(true);
  74587. }
  74588. if (options.poleTargetMesh) {
  74589. this.poleTargetMesh = options.poleTargetMesh;
  74590. this.poleTargetMesh.computeWorldMatrix(true);
  74591. }
  74592. else if (options.poleTargetBone) {
  74593. this.poleTargetBone = options.poleTargetBone;
  74594. }
  74595. else if (this._bone1.getParent()) {
  74596. this.poleTargetBone = this._bone1.getParent();
  74597. }
  74598. if (options.poleTargetLocalOffset) {
  74599. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  74600. }
  74601. if (options.poleAngle) {
  74602. this.poleAngle = options.poleAngle;
  74603. }
  74604. if (options.bendAxis) {
  74605. this._bendAxis.copyFrom(options.bendAxis);
  74606. }
  74607. if (options.maxAngle) {
  74608. this.maxAngle = options.maxAngle;
  74609. }
  74610. if (options.slerpAmount) {
  74611. this.slerpAmount = options.slerpAmount;
  74612. }
  74613. }
  74614. }
  74615. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  74616. get: function () {
  74617. return this._maxAngle;
  74618. },
  74619. set: function (value) {
  74620. this._setMaxAngle(value);
  74621. },
  74622. enumerable: true,
  74623. configurable: true
  74624. });
  74625. BoneIKController.prototype._setMaxAngle = function (ang) {
  74626. if (ang < 0) {
  74627. ang = 0;
  74628. }
  74629. if (ang > Math.PI || ang == undefined) {
  74630. ang = Math.PI;
  74631. }
  74632. this._maxAngle = ang;
  74633. var a = this._bone1Length;
  74634. var b = this._bone2Length;
  74635. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  74636. };
  74637. BoneIKController.prototype.update = function () {
  74638. var bone1 = this._bone1;
  74639. if (!bone1) {
  74640. return;
  74641. }
  74642. var target = this.targetPosition;
  74643. var poleTarget = this.poleTargetPosition;
  74644. var mat1 = BoneIKController._tmpMats[0];
  74645. var mat2 = BoneIKController._tmpMats[1];
  74646. if (this.targetMesh) {
  74647. target.copyFrom(this.targetMesh.getAbsolutePosition());
  74648. }
  74649. if (this.poleTargetBone) {
  74650. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  74651. }
  74652. else if (this.poleTargetMesh) {
  74653. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  74654. }
  74655. var bonePos = BoneIKController._tmpVecs[0];
  74656. var zaxis = BoneIKController._tmpVecs[1];
  74657. var xaxis = BoneIKController._tmpVecs[2];
  74658. var yaxis = BoneIKController._tmpVecs[3];
  74659. var upAxis = BoneIKController._tmpVecs[4];
  74660. var _tmpQuat = BoneIKController._tmpQuat;
  74661. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  74662. poleTarget.subtractToRef(bonePos, upAxis);
  74663. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  74664. upAxis.y = 1;
  74665. }
  74666. else {
  74667. upAxis.normalize();
  74668. }
  74669. target.subtractToRef(bonePos, yaxis);
  74670. yaxis.normalize();
  74671. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  74672. zaxis.normalize();
  74673. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  74674. xaxis.normalize();
  74675. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  74676. var a = this._bone1Length;
  74677. var b = this._bone2Length;
  74678. var c = BABYLON.Vector3.Distance(bonePos, target);
  74679. if (this._maxReach > 0) {
  74680. c = Math.min(this._maxReach, c);
  74681. }
  74682. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  74683. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  74684. if (acosa > 1) {
  74685. acosa = 1;
  74686. }
  74687. if (acosb > 1) {
  74688. acosb = 1;
  74689. }
  74690. if (acosa < -1) {
  74691. acosa = -1;
  74692. }
  74693. if (acosb < -1) {
  74694. acosb = -1;
  74695. }
  74696. var angA = Math.acos(acosa);
  74697. var angB = Math.acos(acosb);
  74698. var angC = -angA - angB;
  74699. if (this._rightHandedSystem) {
  74700. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  74701. mat2.multiplyToRef(mat1, mat1);
  74702. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  74703. mat2.multiplyToRef(mat1, mat1);
  74704. }
  74705. else {
  74706. var _tmpVec = BoneIKController._tmpVecs[5];
  74707. _tmpVec.copyFrom(this._bendAxis);
  74708. _tmpVec.x *= -1;
  74709. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  74710. mat2.multiplyToRef(mat1, mat1);
  74711. }
  74712. if (this.poleAngle) {
  74713. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  74714. mat1.multiplyToRef(mat2, mat1);
  74715. }
  74716. if (this._bone1) {
  74717. if (this.slerpAmount < 1) {
  74718. if (!this._slerping) {
  74719. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  74720. }
  74721. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  74722. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  74723. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  74724. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  74725. this._slerping = true;
  74726. }
  74727. else {
  74728. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  74729. this._bone1Mat.copyFrom(mat1);
  74730. this._slerping = false;
  74731. }
  74732. }
  74733. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  74734. this._bone2Ang = angC;
  74735. };
  74736. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74737. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  74738. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74739. return BoneIKController;
  74740. }());
  74741. BABYLON.BoneIKController = BoneIKController;
  74742. })(BABYLON || (BABYLON = {}));
  74743. //# sourceMappingURL=babylon.boneIKController.js.map
  74744. "use strict";
  74745. var BABYLON;
  74746. (function (BABYLON) {
  74747. var BoneLookController = /** @class */ (function () {
  74748. /**
  74749. * Create a BoneLookController
  74750. * @param mesh the mesh that the bone belongs to
  74751. * @param bone the bone that will be looking to the target
  74752. * @param target the target Vector3 to look at
  74753. * @param settings optional settings:
  74754. * - maxYaw: the maximum angle the bone will yaw to
  74755. * - minYaw: the minimum angle the bone will yaw to
  74756. * - maxPitch: the maximum angle the bone will pitch to
  74757. * - minPitch: the minimum angle the bone will yaw to
  74758. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  74759. * - upAxis: the up axis of the coordinate system
  74760. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  74761. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  74762. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  74763. * - adjustYaw: used to make an adjustment to the yaw of the bone
  74764. * - adjustPitch: used to make an adjustment to the pitch of the bone
  74765. * - adjustRoll: used to make an adjustment to the roll of the bone
  74766. **/
  74767. function BoneLookController(mesh, bone, target, options) {
  74768. /**
  74769. * The up axis of the coordinate system that is used when the bone is rotated.
  74770. */
  74771. this.upAxis = BABYLON.Vector3.Up();
  74772. /**
  74773. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  74774. */
  74775. this.upAxisSpace = BABYLON.Space.LOCAL;
  74776. /**
  74777. * Used to make an adjustment to the yaw of the bone.
  74778. */
  74779. this.adjustYaw = 0;
  74780. /**
  74781. * Used to make an adjustment to the pitch of the bone.
  74782. */
  74783. this.adjustPitch = 0;
  74784. /**
  74785. * Used to make an adjustment to the roll of the bone.
  74786. */
  74787. this.adjustRoll = 0;
  74788. /**
  74789. * 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).
  74790. */
  74791. this.slerpAmount = 1;
  74792. this._boneQuat = BABYLON.Quaternion.Identity();
  74793. this._slerping = false;
  74794. this._firstFrameSkipped = false;
  74795. this._fowardAxis = BABYLON.Vector3.Forward();
  74796. this.mesh = mesh;
  74797. this.bone = bone;
  74798. this.target = target;
  74799. if (options) {
  74800. if (options.adjustYaw) {
  74801. this.adjustYaw = options.adjustYaw;
  74802. }
  74803. if (options.adjustPitch) {
  74804. this.adjustPitch = options.adjustPitch;
  74805. }
  74806. if (options.adjustRoll) {
  74807. this.adjustRoll = options.adjustRoll;
  74808. }
  74809. if (options.maxYaw != null) {
  74810. this.maxYaw = options.maxYaw;
  74811. }
  74812. else {
  74813. this.maxYaw = Math.PI;
  74814. }
  74815. if (options.minYaw != null) {
  74816. this.minYaw = options.minYaw;
  74817. }
  74818. else {
  74819. this.minYaw = -Math.PI;
  74820. }
  74821. if (options.maxPitch != null) {
  74822. this.maxPitch = options.maxPitch;
  74823. }
  74824. else {
  74825. this.maxPitch = Math.PI;
  74826. }
  74827. if (options.minPitch != null) {
  74828. this.minPitch = options.minPitch;
  74829. }
  74830. else {
  74831. this.minPitch = -Math.PI;
  74832. }
  74833. if (options.slerpAmount != null) {
  74834. this.slerpAmount = options.slerpAmount;
  74835. }
  74836. if (options.upAxis != null) {
  74837. this.upAxis = options.upAxis;
  74838. }
  74839. if (options.upAxisSpace != null) {
  74840. this.upAxisSpace = options.upAxisSpace;
  74841. }
  74842. if (options.yawAxis != null || options.pitchAxis != null) {
  74843. var newYawAxis = BABYLON.Axis.Y;
  74844. var newPitchAxis = BABYLON.Axis.X;
  74845. if (options.yawAxis != null) {
  74846. newYawAxis = options.yawAxis.clone();
  74847. newYawAxis.normalize();
  74848. }
  74849. if (options.pitchAxis != null) {
  74850. newPitchAxis = options.pitchAxis.clone();
  74851. newPitchAxis.normalize();
  74852. }
  74853. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  74854. this._transformYawPitch = BABYLON.Matrix.Identity();
  74855. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  74856. this._transformYawPitchInv = this._transformYawPitch.clone();
  74857. this._transformYawPitch.invert();
  74858. }
  74859. }
  74860. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  74861. this.upAxisSpace = BABYLON.Space.LOCAL;
  74862. }
  74863. }
  74864. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  74865. /**
  74866. * Get/set the minimum yaw angle that the bone can look to.
  74867. */
  74868. get: function () {
  74869. return this._minYaw;
  74870. },
  74871. set: function (value) {
  74872. this._minYaw = value;
  74873. this._minYawSin = Math.sin(value);
  74874. this._minYawCos = Math.cos(value);
  74875. if (this._maxYaw != null) {
  74876. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  74877. this._yawRange = this._maxYaw - this._minYaw;
  74878. }
  74879. },
  74880. enumerable: true,
  74881. configurable: true
  74882. });
  74883. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  74884. /**
  74885. * Get/set the maximum yaw angle that the bone can look to.
  74886. */
  74887. get: function () {
  74888. return this._maxYaw;
  74889. },
  74890. set: function (value) {
  74891. this._maxYaw = value;
  74892. this._maxYawSin = Math.sin(value);
  74893. this._maxYawCos = Math.cos(value);
  74894. if (this._minYaw != null) {
  74895. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  74896. this._yawRange = this._maxYaw - this._minYaw;
  74897. }
  74898. },
  74899. enumerable: true,
  74900. configurable: true
  74901. });
  74902. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  74903. /**
  74904. * Get/set the minimum pitch angle that the bone can look to.
  74905. */
  74906. get: function () {
  74907. return this._minPitch;
  74908. },
  74909. set: function (value) {
  74910. this._minPitch = value;
  74911. this._minPitchTan = Math.tan(value);
  74912. },
  74913. enumerable: true,
  74914. configurable: true
  74915. });
  74916. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  74917. /**
  74918. * Get/set the maximum pitch angle that the bone can look to.
  74919. */
  74920. get: function () {
  74921. return this._maxPitch;
  74922. },
  74923. set: function (value) {
  74924. this._maxPitch = value;
  74925. this._maxPitchTan = Math.tan(value);
  74926. },
  74927. enumerable: true,
  74928. configurable: true
  74929. });
  74930. /**
  74931. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  74932. */
  74933. BoneLookController.prototype.update = function () {
  74934. //skip the first frame when slerping so that the mesh rotation is correct
  74935. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  74936. this._firstFrameSkipped = true;
  74937. return;
  74938. }
  74939. var bone = this.bone;
  74940. var bonePos = BoneLookController._tmpVecs[0];
  74941. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  74942. var target = this.target;
  74943. var _tmpMat1 = BoneLookController._tmpMats[0];
  74944. var _tmpMat2 = BoneLookController._tmpMats[1];
  74945. var mesh = this.mesh;
  74946. var parentBone = bone.getParent();
  74947. var upAxis = BoneLookController._tmpVecs[1];
  74948. upAxis.copyFrom(this.upAxis);
  74949. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  74950. if (this._transformYawPitch) {
  74951. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  74952. }
  74953. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  74954. }
  74955. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  74956. mesh.getDirectionToRef(upAxis, upAxis);
  74957. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  74958. upAxis.normalize();
  74959. }
  74960. }
  74961. var checkYaw = false;
  74962. var checkPitch = false;
  74963. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  74964. checkYaw = true;
  74965. }
  74966. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  74967. checkPitch = true;
  74968. }
  74969. if (checkYaw || checkPitch) {
  74970. var spaceMat = BoneLookController._tmpMats[2];
  74971. var spaceMatInv = BoneLookController._tmpMats[3];
  74972. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  74973. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  74974. }
  74975. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  74976. spaceMat.copyFrom(mesh.getWorldMatrix());
  74977. }
  74978. else {
  74979. var forwardAxis = BoneLookController._tmpVecs[2];
  74980. forwardAxis.copyFrom(this._fowardAxis);
  74981. if (this._transformYawPitch) {
  74982. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  74983. }
  74984. if (parentBone) {
  74985. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  74986. }
  74987. else {
  74988. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  74989. }
  74990. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  74991. rightAxis.normalize();
  74992. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  74993. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  74994. }
  74995. spaceMat.invertToRef(spaceMatInv);
  74996. var xzlen = null;
  74997. if (checkPitch) {
  74998. var localTarget = BoneLookController._tmpVecs[3];
  74999. target.subtractToRef(bonePos, localTarget);
  75000. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  75001. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  75002. var pitch = Math.atan2(localTarget.y, xzlen);
  75003. var newPitch = pitch;
  75004. if (pitch > this._maxPitch) {
  75005. localTarget.y = this._maxPitchTan * xzlen;
  75006. newPitch = this._maxPitch;
  75007. }
  75008. else if (pitch < this._minPitch) {
  75009. localTarget.y = this._minPitchTan * xzlen;
  75010. newPitch = this._minPitch;
  75011. }
  75012. if (pitch != newPitch) {
  75013. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  75014. localTarget.addInPlace(bonePos);
  75015. target = localTarget;
  75016. }
  75017. }
  75018. if (checkYaw) {
  75019. var localTarget = BoneLookController._tmpVecs[4];
  75020. target.subtractToRef(bonePos, localTarget);
  75021. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  75022. var yaw = Math.atan2(localTarget.x, localTarget.z);
  75023. var newYaw = yaw;
  75024. if (yaw > this._maxYaw || yaw < this._minYaw) {
  75025. if (xzlen == null) {
  75026. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  75027. }
  75028. if (this._yawRange > Math.PI) {
  75029. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  75030. localTarget.z = this._maxYawCos * xzlen;
  75031. localTarget.x = this._maxYawSin * xzlen;
  75032. newYaw = this._maxYaw;
  75033. }
  75034. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  75035. localTarget.z = this._minYawCos * xzlen;
  75036. localTarget.x = this._minYawSin * xzlen;
  75037. newYaw = this._minYaw;
  75038. }
  75039. }
  75040. else {
  75041. if (yaw > this._maxYaw) {
  75042. localTarget.z = this._maxYawCos * xzlen;
  75043. localTarget.x = this._maxYawSin * xzlen;
  75044. newYaw = this._maxYaw;
  75045. }
  75046. else if (yaw < this._minYaw) {
  75047. localTarget.z = this._minYawCos * xzlen;
  75048. localTarget.x = this._minYawSin * xzlen;
  75049. newYaw = this._minYaw;
  75050. }
  75051. }
  75052. }
  75053. if (this._slerping && this._yawRange > Math.PI) {
  75054. //are we going to be crossing into the min/max region?
  75055. var boneFwd = BoneLookController._tmpVecs[8];
  75056. boneFwd.copyFrom(BABYLON.Axis.Z);
  75057. if (this._transformYawPitch) {
  75058. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  75059. }
  75060. var boneRotMat = BoneLookController._tmpMats[4];
  75061. this._boneQuat.toRotationMatrix(boneRotMat);
  75062. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  75063. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  75064. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  75065. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  75066. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  75067. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  75068. if (angBtwTar > angBtwMidYaw) {
  75069. if (xzlen == null) {
  75070. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  75071. }
  75072. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  75073. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  75074. if (angBtwMin < angBtwMax) {
  75075. newYaw = boneYaw + Math.PI * .75;
  75076. localTarget.z = Math.cos(newYaw) * xzlen;
  75077. localTarget.x = Math.sin(newYaw) * xzlen;
  75078. }
  75079. else {
  75080. newYaw = boneYaw - Math.PI * .75;
  75081. localTarget.z = Math.cos(newYaw) * xzlen;
  75082. localTarget.x = Math.sin(newYaw) * xzlen;
  75083. }
  75084. }
  75085. }
  75086. if (yaw != newYaw) {
  75087. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  75088. localTarget.addInPlace(bonePos);
  75089. target = localTarget;
  75090. }
  75091. }
  75092. }
  75093. var zaxis = BoneLookController._tmpVecs[5];
  75094. var xaxis = BoneLookController._tmpVecs[6];
  75095. var yaxis = BoneLookController._tmpVecs[7];
  75096. var _tmpQuat = BoneLookController._tmpQuat;
  75097. target.subtractToRef(bonePos, zaxis);
  75098. zaxis.normalize();
  75099. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  75100. xaxis.normalize();
  75101. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  75102. yaxis.normalize();
  75103. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  75104. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  75105. return;
  75106. }
  75107. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  75108. return;
  75109. }
  75110. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  75111. return;
  75112. }
  75113. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  75114. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  75115. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  75116. }
  75117. if (this.slerpAmount < 1) {
  75118. if (!this._slerping) {
  75119. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  75120. }
  75121. if (this._transformYawPitch) {
  75122. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  75123. }
  75124. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  75125. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  75126. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  75127. this._slerping = true;
  75128. }
  75129. else {
  75130. if (this._transformYawPitch) {
  75131. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  75132. }
  75133. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  75134. this._slerping = false;
  75135. }
  75136. };
  75137. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  75138. var angDiff = ang2 - ang1;
  75139. angDiff %= Math.PI * 2;
  75140. if (angDiff > Math.PI) {
  75141. angDiff -= Math.PI * 2;
  75142. }
  75143. else if (angDiff < -Math.PI) {
  75144. angDiff += Math.PI * 2;
  75145. }
  75146. return angDiff;
  75147. };
  75148. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  75149. ang1 %= (2 * Math.PI);
  75150. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  75151. ang2 %= (2 * Math.PI);
  75152. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  75153. var ab = 0;
  75154. if (ang1 < ang2) {
  75155. ab = ang2 - ang1;
  75156. }
  75157. else {
  75158. ab = ang1 - ang2;
  75159. }
  75160. if (ab > Math.PI) {
  75161. ab = Math.PI * 2 - ab;
  75162. }
  75163. return ab;
  75164. };
  75165. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  75166. ang %= (2 * Math.PI);
  75167. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  75168. ang1 %= (2 * Math.PI);
  75169. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  75170. ang2 %= (2 * Math.PI);
  75171. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  75172. if (ang1 < ang2) {
  75173. if (ang > ang1 && ang < ang2) {
  75174. return true;
  75175. }
  75176. }
  75177. else {
  75178. if (ang > ang2 && ang < ang1) {
  75179. return true;
  75180. }
  75181. }
  75182. return false;
  75183. };
  75184. 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()];
  75185. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  75186. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  75187. return BoneLookController;
  75188. }());
  75189. BABYLON.BoneLookController = BoneLookController;
  75190. })(BABYLON || (BABYLON = {}));
  75191. //# sourceMappingURL=babylon.boneLookController.js.map
  75192. "use strict";
  75193. var BABYLON;
  75194. (function (BABYLON) {
  75195. var Skeleton = /** @class */ (function () {
  75196. function Skeleton(name, id, scene) {
  75197. this.name = name;
  75198. this.id = id;
  75199. this.bones = new Array();
  75200. this.needInitialSkinMatrix = false;
  75201. this._isDirty = true;
  75202. this._meshesWithPoseMatrix = new Array();
  75203. this._identity = BABYLON.Matrix.Identity();
  75204. this._ranges = {};
  75205. this._lastAbsoluteTransformsUpdateId = -1;
  75206. /**
  75207. * Specifies if the skeleton should be serialized.
  75208. */
  75209. this.doNotSerialize = false;
  75210. // Events
  75211. /**
  75212. * An event triggered before computing the skeleton's matrices
  75213. */
  75214. this.onBeforeComputeObservable = new BABYLON.Observable();
  75215. this.bones = [];
  75216. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75217. scene.skeletons.push(this);
  75218. //make sure it will recalculate the matrix next time prepare is called.
  75219. this._isDirty = true;
  75220. }
  75221. // Members
  75222. Skeleton.prototype.getTransformMatrices = function (mesh) {
  75223. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  75224. return mesh._bonesTransformMatrices;
  75225. }
  75226. if (!this._transformMatrices) {
  75227. this.prepare();
  75228. }
  75229. return this._transformMatrices;
  75230. };
  75231. Skeleton.prototype.getScene = function () {
  75232. return this._scene;
  75233. };
  75234. // Methods
  75235. /**
  75236. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  75237. */
  75238. Skeleton.prototype.toString = function (fullDetails) {
  75239. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  75240. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  75241. if (fullDetails) {
  75242. ret += ", Ranges: {";
  75243. var first = true;
  75244. for (var name_1 in this._ranges) {
  75245. if (first) {
  75246. ret += ", ";
  75247. first = false;
  75248. }
  75249. ret += name_1;
  75250. }
  75251. ret += "}";
  75252. }
  75253. return ret;
  75254. };
  75255. /**
  75256. * Get bone's index searching by name
  75257. * @param {string} name is bone's name to search for
  75258. * @return {number} Indice of the bone. Returns -1 if not found
  75259. */
  75260. Skeleton.prototype.getBoneIndexByName = function (name) {
  75261. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  75262. if (this.bones[boneIndex].name === name) {
  75263. return boneIndex;
  75264. }
  75265. }
  75266. return -1;
  75267. };
  75268. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  75269. // check name not already in use
  75270. if (!this._ranges[name]) {
  75271. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  75272. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  75273. if (this.bones[i].animations[0]) {
  75274. this.bones[i].animations[0].createRange(name, from, to);
  75275. }
  75276. }
  75277. }
  75278. };
  75279. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  75280. if (deleteFrames === void 0) { deleteFrames = true; }
  75281. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  75282. if (this.bones[i].animations[0]) {
  75283. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  75284. }
  75285. }
  75286. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  75287. };
  75288. Skeleton.prototype.getAnimationRange = function (name) {
  75289. return this._ranges[name];
  75290. };
  75291. /**
  75292. * Returns as an Array, all AnimationRanges defined on this skeleton
  75293. */
  75294. Skeleton.prototype.getAnimationRanges = function () {
  75295. var animationRanges = [];
  75296. var name;
  75297. var i = 0;
  75298. for (name in this._ranges) {
  75299. animationRanges[i] = this._ranges[name];
  75300. i++;
  75301. }
  75302. return animationRanges;
  75303. };
  75304. /**
  75305. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  75306. */
  75307. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  75308. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  75309. if (this._ranges[name] || !source.getAnimationRange(name)) {
  75310. return false;
  75311. }
  75312. var ret = true;
  75313. var frameOffset = this._getHighestAnimationFrame() + 1;
  75314. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  75315. var boneDict = {};
  75316. var sourceBones = source.bones;
  75317. var nBones;
  75318. var i;
  75319. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  75320. boneDict[sourceBones[i].name] = sourceBones[i];
  75321. }
  75322. if (this.bones.length !== sourceBones.length) {
  75323. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  75324. ret = false;
  75325. }
  75326. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  75327. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  75328. var boneName = this.bones[i].name;
  75329. var sourceBone = boneDict[boneName];
  75330. if (sourceBone) {
  75331. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  75332. }
  75333. else {
  75334. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  75335. ret = false;
  75336. }
  75337. }
  75338. // do not call createAnimationRange(), since it also is done to bones, which was already done
  75339. var range = source.getAnimationRange(name);
  75340. if (range) {
  75341. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  75342. }
  75343. return ret;
  75344. };
  75345. Skeleton.prototype.returnToRest = function () {
  75346. for (var index = 0; index < this.bones.length; index++) {
  75347. this.bones[index].returnToRest();
  75348. }
  75349. };
  75350. Skeleton.prototype._getHighestAnimationFrame = function () {
  75351. var ret = 0;
  75352. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  75353. if (this.bones[i].animations[0]) {
  75354. var highest = this.bones[i].animations[0].getHighestFrame();
  75355. if (ret < highest) {
  75356. ret = highest;
  75357. }
  75358. }
  75359. }
  75360. return ret;
  75361. };
  75362. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  75363. var range = this.getAnimationRange(name);
  75364. if (!range) {
  75365. return null;
  75366. }
  75367. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  75368. };
  75369. Skeleton.prototype._markAsDirty = function () {
  75370. this._isDirty = true;
  75371. };
  75372. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  75373. this._meshesWithPoseMatrix.push(mesh);
  75374. };
  75375. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  75376. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  75377. if (index > -1) {
  75378. this._meshesWithPoseMatrix.splice(index, 1);
  75379. }
  75380. };
  75381. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  75382. this.onBeforeComputeObservable.notifyObservers(this);
  75383. for (var index = 0; index < this.bones.length; index++) {
  75384. var bone = this.bones[index];
  75385. var parentBone = bone.getParent();
  75386. if (parentBone) {
  75387. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  75388. }
  75389. else {
  75390. if (initialSkinMatrix) {
  75391. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  75392. }
  75393. else {
  75394. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  75395. }
  75396. }
  75397. if (bone._index !== -1) {
  75398. var mappedIndex = bone._index === null ? index : bone._index;
  75399. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  75400. }
  75401. }
  75402. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  75403. };
  75404. Skeleton.prototype.prepare = function () {
  75405. if (!this._isDirty) {
  75406. return;
  75407. }
  75408. if (this.needInitialSkinMatrix) {
  75409. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  75410. var mesh = this._meshesWithPoseMatrix[index];
  75411. var poseMatrix = mesh.getPoseMatrix();
  75412. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  75413. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  75414. }
  75415. if (this._synchronizedWithMesh !== mesh) {
  75416. this._synchronizedWithMesh = mesh;
  75417. // Prepare bones
  75418. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  75419. var bone = this.bones[boneIndex];
  75420. if (!bone.getParent()) {
  75421. var matrix = bone.getBaseMatrix();
  75422. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  75423. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  75424. }
  75425. }
  75426. }
  75427. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  75428. }
  75429. }
  75430. else {
  75431. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  75432. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  75433. }
  75434. this._computeTransformMatrices(this._transformMatrices, null);
  75435. }
  75436. this._isDirty = false;
  75437. this._scene._activeBones.addCount(this.bones.length, false);
  75438. };
  75439. Skeleton.prototype.getAnimatables = function () {
  75440. if (!this._animatables || this._animatables.length !== this.bones.length) {
  75441. this._animatables = [];
  75442. for (var index = 0; index < this.bones.length; index++) {
  75443. this._animatables.push(this.bones[index]);
  75444. }
  75445. }
  75446. return this._animatables;
  75447. };
  75448. Skeleton.prototype.clone = function (name, id) {
  75449. var result = new Skeleton(name, id || name, this._scene);
  75450. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  75451. for (var index = 0; index < this.bones.length; index++) {
  75452. var source = this.bones[index];
  75453. var parentBone = null;
  75454. var parent_1 = source.getParent();
  75455. if (parent_1) {
  75456. var parentIndex = this.bones.indexOf(parent_1);
  75457. parentBone = result.bones[parentIndex];
  75458. }
  75459. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  75460. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  75461. }
  75462. if (this._ranges) {
  75463. result._ranges = {};
  75464. for (var rangeName in this._ranges) {
  75465. var range = this._ranges[rangeName];
  75466. if (range) {
  75467. result._ranges[rangeName] = range.clone();
  75468. }
  75469. }
  75470. }
  75471. this._isDirty = true;
  75472. return result;
  75473. };
  75474. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  75475. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  75476. this.bones.forEach(function (bone) {
  75477. bone.animations.forEach(function (animation) {
  75478. animation.enableBlending = true;
  75479. animation.blendingSpeed = blendingSpeed;
  75480. });
  75481. });
  75482. };
  75483. Skeleton.prototype.dispose = function () {
  75484. this._meshesWithPoseMatrix = [];
  75485. // Animations
  75486. this.getScene().stopAnimation(this);
  75487. // Remove from scene
  75488. this.getScene().removeSkeleton(this);
  75489. };
  75490. Skeleton.prototype.serialize = function () {
  75491. var serializationObject = {};
  75492. serializationObject.name = this.name;
  75493. serializationObject.id = this.id;
  75494. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  75495. serializationObject.bones = [];
  75496. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  75497. for (var index = 0; index < this.bones.length; index++) {
  75498. var bone = this.bones[index];
  75499. var parent_2 = bone.getParent();
  75500. var serializedBone = {
  75501. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  75502. name: bone.name,
  75503. matrix: bone.getBaseMatrix().toArray(),
  75504. rest: bone.getRestPose().toArray()
  75505. };
  75506. serializationObject.bones.push(serializedBone);
  75507. if (bone.length) {
  75508. serializedBone.length = bone.length;
  75509. }
  75510. if (bone.animations && bone.animations.length > 0) {
  75511. serializedBone.animation = bone.animations[0].serialize();
  75512. }
  75513. serializationObject.ranges = [];
  75514. for (var name in this._ranges) {
  75515. var source = this._ranges[name];
  75516. if (!source) {
  75517. continue;
  75518. }
  75519. var range = {};
  75520. range.name = name;
  75521. range.from = source.from;
  75522. range.to = source.to;
  75523. serializationObject.ranges.push(range);
  75524. }
  75525. }
  75526. return serializationObject;
  75527. };
  75528. Skeleton.Parse = function (parsedSkeleton, scene) {
  75529. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  75530. if (parsedSkeleton.dimensionsAtRest) {
  75531. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  75532. }
  75533. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  75534. var index;
  75535. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  75536. var parsedBone = parsedSkeleton.bones[index];
  75537. var parentBone = null;
  75538. if (parsedBone.parentBoneIndex > -1) {
  75539. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  75540. }
  75541. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  75542. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  75543. if (parsedBone.length) {
  75544. bone.length = parsedBone.length;
  75545. }
  75546. if (parsedBone.animation) {
  75547. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  75548. }
  75549. }
  75550. // placed after bones, so createAnimationRange can cascade down
  75551. if (parsedSkeleton.ranges) {
  75552. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  75553. var data = parsedSkeleton.ranges[index];
  75554. skeleton.createAnimationRange(data.name, data.from, data.to);
  75555. }
  75556. }
  75557. return skeleton;
  75558. };
  75559. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  75560. if (forceUpdate === void 0) { forceUpdate = false; }
  75561. var renderId = this._scene.getRenderId();
  75562. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  75563. this.bones[0].computeAbsoluteTransforms();
  75564. this._lastAbsoluteTransformsUpdateId = renderId;
  75565. }
  75566. };
  75567. Skeleton.prototype.getPoseMatrix = function () {
  75568. var poseMatrix = null;
  75569. if (this._meshesWithPoseMatrix.length > 0) {
  75570. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  75571. }
  75572. return poseMatrix;
  75573. };
  75574. Skeleton.prototype.sortBones = function () {
  75575. var bones = new Array();
  75576. var visited = new Array(this.bones.length);
  75577. for (var index = 0; index < this.bones.length; index++) {
  75578. this._sortBones(index, bones, visited);
  75579. }
  75580. this.bones = bones;
  75581. };
  75582. Skeleton.prototype._sortBones = function (index, bones, visited) {
  75583. if (visited[index]) {
  75584. return;
  75585. }
  75586. visited[index] = true;
  75587. var bone = this.bones[index];
  75588. if (bone._index === undefined) {
  75589. bone._index = index;
  75590. }
  75591. var parentBone = bone.getParent();
  75592. if (parentBone) {
  75593. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  75594. }
  75595. bones.push(bone);
  75596. };
  75597. return Skeleton;
  75598. }());
  75599. BABYLON.Skeleton = Skeleton;
  75600. })(BABYLON || (BABYLON = {}));
  75601. //# sourceMappingURL=babylon.skeleton.js.map
  75602. "use strict";
  75603. var BABYLON;
  75604. (function (BABYLON) {
  75605. var SphericalPolynomial = /** @class */ (function () {
  75606. function SphericalPolynomial() {
  75607. this.x = BABYLON.Vector3.Zero();
  75608. this.y = BABYLON.Vector3.Zero();
  75609. this.z = BABYLON.Vector3.Zero();
  75610. this.xx = BABYLON.Vector3.Zero();
  75611. this.yy = BABYLON.Vector3.Zero();
  75612. this.zz = BABYLON.Vector3.Zero();
  75613. this.xy = BABYLON.Vector3.Zero();
  75614. this.yz = BABYLON.Vector3.Zero();
  75615. this.zx = BABYLON.Vector3.Zero();
  75616. }
  75617. SphericalPolynomial.prototype.addAmbient = function (color) {
  75618. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  75619. this.xx = this.xx.add(colorVector);
  75620. this.yy = this.yy.add(colorVector);
  75621. this.zz = this.zz.add(colorVector);
  75622. };
  75623. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  75624. var result = new SphericalPolynomial();
  75625. result.x = harmonics.L11.scale(1.02333);
  75626. result.y = harmonics.L1_1.scale(1.02333);
  75627. result.z = harmonics.L10.scale(1.02333);
  75628. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  75629. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  75630. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  75631. result.yz = harmonics.L2_1.scale(0.858086);
  75632. result.zx = harmonics.L21.scale(0.858086);
  75633. result.xy = harmonics.L2_2.scale(0.858086);
  75634. result.scale(1.0 / Math.PI);
  75635. return result;
  75636. };
  75637. SphericalPolynomial.prototype.scale = function (scale) {
  75638. this.x = this.x.scale(scale);
  75639. this.y = this.y.scale(scale);
  75640. this.z = this.z.scale(scale);
  75641. this.xx = this.xx.scale(scale);
  75642. this.yy = this.yy.scale(scale);
  75643. this.zz = this.zz.scale(scale);
  75644. this.yz = this.yz.scale(scale);
  75645. this.zx = this.zx.scale(scale);
  75646. this.xy = this.xy.scale(scale);
  75647. };
  75648. return SphericalPolynomial;
  75649. }());
  75650. BABYLON.SphericalPolynomial = SphericalPolynomial;
  75651. var SphericalHarmonics = /** @class */ (function () {
  75652. function SphericalHarmonics() {
  75653. this.L00 = BABYLON.Vector3.Zero();
  75654. this.L1_1 = BABYLON.Vector3.Zero();
  75655. this.L10 = BABYLON.Vector3.Zero();
  75656. this.L11 = BABYLON.Vector3.Zero();
  75657. this.L2_2 = BABYLON.Vector3.Zero();
  75658. this.L2_1 = BABYLON.Vector3.Zero();
  75659. this.L20 = BABYLON.Vector3.Zero();
  75660. this.L21 = BABYLON.Vector3.Zero();
  75661. this.L22 = BABYLON.Vector3.Zero();
  75662. }
  75663. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  75664. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  75665. var c = colorVector.scale(deltaSolidAngle);
  75666. this.L00 = this.L00.add(c.scale(0.282095));
  75667. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  75668. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  75669. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  75670. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  75671. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  75672. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  75673. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  75674. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  75675. };
  75676. SphericalHarmonics.prototype.scale = function (scale) {
  75677. this.L00 = this.L00.scale(scale);
  75678. this.L1_1 = this.L1_1.scale(scale);
  75679. this.L10 = this.L10.scale(scale);
  75680. this.L11 = this.L11.scale(scale);
  75681. this.L2_2 = this.L2_2.scale(scale);
  75682. this.L2_1 = this.L2_1.scale(scale);
  75683. this.L20 = this.L20.scale(scale);
  75684. this.L21 = this.L21.scale(scale);
  75685. this.L22 = this.L22.scale(scale);
  75686. };
  75687. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  75688. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  75689. //
  75690. // E_lm = A_l * L_lm
  75691. //
  75692. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  75693. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  75694. // the scaling factors are given in equation 9.
  75695. // Constant (Band 0)
  75696. this.L00 = this.L00.scale(3.141593);
  75697. // Linear (Band 1)
  75698. this.L1_1 = this.L1_1.scale(2.094395);
  75699. this.L10 = this.L10.scale(2.094395);
  75700. this.L11 = this.L11.scale(2.094395);
  75701. // Quadratic (Band 2)
  75702. this.L2_2 = this.L2_2.scale(0.785398);
  75703. this.L2_1 = this.L2_1.scale(0.785398);
  75704. this.L20 = this.L20.scale(0.785398);
  75705. this.L21 = this.L21.scale(0.785398);
  75706. this.L22 = this.L22.scale(0.785398);
  75707. };
  75708. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  75709. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  75710. // L = (1/pi) * E * rho
  75711. //
  75712. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  75713. this.scale(1.0 / Math.PI);
  75714. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  75715. // (The pixel shader must apply albedo after texture fetches, etc).
  75716. };
  75717. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  75718. var result = new SphericalHarmonics();
  75719. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  75720. result.L1_1 = polynomial.y.scale(0.977204);
  75721. result.L10 = polynomial.z.scale(0.977204);
  75722. result.L11 = polynomial.x.scale(0.977204);
  75723. result.L2_2 = polynomial.xy.scale(1.16538);
  75724. result.L2_1 = polynomial.yz.scale(1.16538);
  75725. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  75726. result.L21 = polynomial.zx.scale(1.16538);
  75727. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  75728. result.scale(Math.PI);
  75729. return result;
  75730. };
  75731. return SphericalHarmonics;
  75732. }());
  75733. BABYLON.SphericalHarmonics = SphericalHarmonics;
  75734. })(BABYLON || (BABYLON = {}));
  75735. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  75736. "use strict";
  75737. var BABYLON;
  75738. (function (BABYLON) {
  75739. var FileFaceOrientation = /** @class */ (function () {
  75740. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  75741. this.name = name;
  75742. this.worldAxisForNormal = worldAxisForNormal;
  75743. this.worldAxisForFileX = worldAxisForFileX;
  75744. this.worldAxisForFileY = worldAxisForFileY;
  75745. }
  75746. return FileFaceOrientation;
  75747. }());
  75748. ;
  75749. /**
  75750. * Helper class dealing with the extraction of spherical polynomial dataArray
  75751. * from a cube map.
  75752. */
  75753. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  75754. function CubeMapToSphericalPolynomialTools() {
  75755. }
  75756. /**
  75757. * Converts a texture to the according Spherical Polynomial data.
  75758. * This extracts the first 3 orders only as they are the only one used in the lighting.
  75759. *
  75760. * @param texture The texture to extract the information from.
  75761. * @return The Spherical Polynomial data.
  75762. */
  75763. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  75764. if (!texture.isCube) {
  75765. // Only supports cube Textures currently.
  75766. return null;
  75767. }
  75768. var size = texture.getSize().width;
  75769. var right = texture.readPixels(0);
  75770. var left = texture.readPixels(1);
  75771. var up;
  75772. var down;
  75773. if (texture.isRenderTarget) {
  75774. up = texture.readPixels(3);
  75775. down = texture.readPixels(2);
  75776. }
  75777. else {
  75778. up = texture.readPixels(2);
  75779. down = texture.readPixels(3);
  75780. }
  75781. var front = texture.readPixels(4);
  75782. var back = texture.readPixels(5);
  75783. var gammaSpace = texture.gammaSpace;
  75784. // Always read as RGBA.
  75785. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  75786. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75787. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75788. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75789. }
  75790. var cubeInfo = {
  75791. size: size,
  75792. right: right,
  75793. left: left,
  75794. up: up,
  75795. down: down,
  75796. front: front,
  75797. back: back,
  75798. format: format,
  75799. type: type,
  75800. gammaSpace: gammaSpace,
  75801. };
  75802. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  75803. };
  75804. /**
  75805. * Converts a cubemap to the according Spherical Polynomial data.
  75806. * This extracts the first 3 orders only as they are the only one used in the lighting.
  75807. *
  75808. * @param cubeInfo The Cube map to extract the information from.
  75809. * @return The Spherical Polynomial data.
  75810. */
  75811. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  75812. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  75813. var totalSolidAngle = 0.0;
  75814. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  75815. var du = 2.0 / cubeInfo.size;
  75816. var dv = du;
  75817. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  75818. var minUV = du * 0.5 - 1.0;
  75819. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75820. var fileFace = this.FileFaces[faceIndex];
  75821. var dataArray = cubeInfo[fileFace.name];
  75822. var v = minUV;
  75823. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  75824. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  75825. // Because SP is still linear, so summation is fine in that basis.
  75826. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  75827. for (var y = 0; y < cubeInfo.size; y++) {
  75828. var u = minUV;
  75829. for (var x = 0; x < cubeInfo.size; x++) {
  75830. // World direction (not normalised)
  75831. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  75832. worldDirection.normalize();
  75833. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  75834. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  75835. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  75836. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  75837. // Handle Integer types.
  75838. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75839. r /= 255;
  75840. g /= 255;
  75841. b /= 255;
  75842. }
  75843. // Handle Gamma space textures.
  75844. if (cubeInfo.gammaSpace) {
  75845. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  75846. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  75847. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  75848. }
  75849. var color = new BABYLON.Color3(r, g, b);
  75850. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  75851. totalSolidAngle += deltaSolidAngle;
  75852. u += du;
  75853. }
  75854. v += dv;
  75855. }
  75856. }
  75857. // Solid angle for entire sphere is 4*pi
  75858. var sphereSolidAngle = 4.0 * Math.PI;
  75859. // Adjust the solid angle to allow for how many faces we processed.
  75860. var facesProcessed = 6.0;
  75861. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  75862. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  75863. // This is needed because the numerical integration over the cube uses a
  75864. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  75865. // and also to compensate for accumulative error due to float precision in the summation.
  75866. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  75867. sphericalHarmonics.scale(correctionFactor);
  75868. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  75869. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  75870. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  75871. };
  75872. CubeMapToSphericalPolynomialTools.FileFaces = [
  75873. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  75874. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  75875. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  75876. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  75877. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  75878. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  75879. ];
  75880. return CubeMapToSphericalPolynomialTools;
  75881. }());
  75882. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  75883. })(BABYLON || (BABYLON = {}));
  75884. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  75885. "use strict";
  75886. var BABYLON;
  75887. (function (BABYLON) {
  75888. /**
  75889. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  75890. */
  75891. var PanoramaToCubeMapTools = /** @class */ (function () {
  75892. function PanoramaToCubeMapTools() {
  75893. }
  75894. /**
  75895. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  75896. *
  75897. * @param float32Array The source data.
  75898. * @param inputWidth The width of the input panorama.
  75899. * @param inputhHeight The height of the input panorama.
  75900. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  75901. * @return The cubemap data
  75902. */
  75903. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  75904. if (!float32Array) {
  75905. throw "ConvertPanoramaToCubemap: input cannot be null";
  75906. }
  75907. if (float32Array.length != inputWidth * inputHeight * 3) {
  75908. throw "ConvertPanoramaToCubemap: input size is wrong";
  75909. }
  75910. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  75911. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  75912. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  75913. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  75914. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  75915. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  75916. return {
  75917. front: textureFront,
  75918. back: textureBack,
  75919. left: textureLeft,
  75920. right: textureRight,
  75921. up: textureUp,
  75922. down: textureDown,
  75923. size: size,
  75924. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  75925. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  75926. gammaSpace: false,
  75927. };
  75928. };
  75929. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  75930. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  75931. var textureArray = new Float32Array(buffer);
  75932. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  75933. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  75934. var dy = 1 / texSize;
  75935. var fy = 0;
  75936. for (var y = 0; y < texSize; y++) {
  75937. var xv1 = faceData[0];
  75938. var xv2 = faceData[2];
  75939. for (var x = 0; x < texSize; x++) {
  75940. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  75941. v.normalize();
  75942. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  75943. // 3 channels per pixels
  75944. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  75945. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  75946. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  75947. xv1 = xv1.add(rotDX1);
  75948. xv2 = xv2.add(rotDX2);
  75949. }
  75950. fy += dy;
  75951. }
  75952. return textureArray;
  75953. };
  75954. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  75955. var theta = Math.atan2(vDir.z, vDir.x);
  75956. var phi = Math.acos(vDir.y);
  75957. while (theta < -Math.PI)
  75958. theta += 2 * Math.PI;
  75959. while (theta > Math.PI)
  75960. theta -= 2 * Math.PI;
  75961. var dx = theta / Math.PI;
  75962. var dy = phi / Math.PI;
  75963. // recenter.
  75964. dx = dx * 0.5 + 0.5;
  75965. var px = Math.round(dx * inputWidth);
  75966. if (px < 0)
  75967. px = 0;
  75968. else if (px >= inputWidth)
  75969. px = inputWidth - 1;
  75970. var py = Math.round(dy * inputHeight);
  75971. if (py < 0)
  75972. py = 0;
  75973. else if (py >= inputHeight)
  75974. py = inputHeight - 1;
  75975. var inputY = (inputHeight - py - 1);
  75976. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  75977. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  75978. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  75979. return {
  75980. r: r,
  75981. g: g,
  75982. b: b
  75983. };
  75984. };
  75985. PanoramaToCubeMapTools.FACE_FRONT = [
  75986. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75987. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75988. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75989. new BABYLON.Vector3(1.0, 1.0, -1.0)
  75990. ];
  75991. PanoramaToCubeMapTools.FACE_BACK = [
  75992. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75993. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75994. new BABYLON.Vector3(1.0, 1.0, 1.0),
  75995. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  75996. ];
  75997. PanoramaToCubeMapTools.FACE_RIGHT = [
  75998. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75999. new BABYLON.Vector3(1.0, -1.0, 1.0),
  76000. new BABYLON.Vector3(1.0, 1.0, -1.0),
  76001. new BABYLON.Vector3(1.0, 1.0, 1.0)
  76002. ];
  76003. PanoramaToCubeMapTools.FACE_LEFT = [
  76004. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  76005. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  76006. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  76007. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  76008. ];
  76009. PanoramaToCubeMapTools.FACE_DOWN = [
  76010. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  76011. new BABYLON.Vector3(1.0, 1.0, -1.0),
  76012. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  76013. new BABYLON.Vector3(1.0, 1.0, 1.0)
  76014. ];
  76015. PanoramaToCubeMapTools.FACE_UP = [
  76016. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  76017. new BABYLON.Vector3(1.0, -1.0, 1.0),
  76018. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  76019. new BABYLON.Vector3(1.0, -1.0, -1.0)
  76020. ];
  76021. return PanoramaToCubeMapTools;
  76022. }());
  76023. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  76024. })(BABYLON || (BABYLON = {}));
  76025. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  76026. "use strict";
  76027. var BABYLON;
  76028. (function (BABYLON) {
  76029. ;
  76030. /**
  76031. * This groups tools to convert HDR texture to native colors array.
  76032. */
  76033. var HDRTools = /** @class */ (function () {
  76034. function HDRTools() {
  76035. }
  76036. HDRTools.Ldexp = function (mantissa, exponent) {
  76037. if (exponent > 1023) {
  76038. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  76039. }
  76040. if (exponent < -1074) {
  76041. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  76042. }
  76043. return mantissa * Math.pow(2, exponent);
  76044. };
  76045. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  76046. if (exponent > 0) {
  76047. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  76048. float32array[index + 0] = red * exponent;
  76049. float32array[index + 1] = green * exponent;
  76050. float32array[index + 2] = blue * exponent;
  76051. }
  76052. else {
  76053. float32array[index + 0] = 0;
  76054. float32array[index + 1] = 0;
  76055. float32array[index + 2] = 0;
  76056. }
  76057. };
  76058. HDRTools.readStringLine = function (uint8array, startIndex) {
  76059. var line = "";
  76060. var character = "";
  76061. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  76062. character = String.fromCharCode(uint8array[i]);
  76063. if (character == "\n") {
  76064. break;
  76065. }
  76066. line += character;
  76067. }
  76068. return line;
  76069. };
  76070. /**
  76071. * Reads header information from an RGBE texture stored in a native array.
  76072. * More information on this format are available here:
  76073. * https://en.wikipedia.org/wiki/RGBE_image_format
  76074. *
  76075. * @param uint8array The binary file stored in native array.
  76076. * @return The header information.
  76077. */
  76078. HDRTools.RGBE_ReadHeader = function (uint8array) {
  76079. var height = 0;
  76080. var width = 0;
  76081. var line = this.readStringLine(uint8array, 0);
  76082. if (line[0] != '#' || line[1] != '?') {
  76083. throw "Bad HDR Format.";
  76084. }
  76085. var endOfHeader = false;
  76086. var findFormat = false;
  76087. var lineIndex = 0;
  76088. do {
  76089. lineIndex += (line.length + 1);
  76090. line = this.readStringLine(uint8array, lineIndex);
  76091. if (line == "FORMAT=32-bit_rle_rgbe") {
  76092. findFormat = true;
  76093. }
  76094. else if (line.length == 0) {
  76095. endOfHeader = true;
  76096. }
  76097. } while (!endOfHeader);
  76098. if (!findFormat) {
  76099. throw "HDR Bad header format, unsupported FORMAT";
  76100. }
  76101. lineIndex += (line.length + 1);
  76102. line = this.readStringLine(uint8array, lineIndex);
  76103. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  76104. var match = sizeRegexp.exec(line);
  76105. // TODO. Support +Y and -X if needed.
  76106. if (!match || match.length < 3) {
  76107. throw "HDR Bad header format, no size";
  76108. }
  76109. width = parseInt(match[2]);
  76110. height = parseInt(match[1]);
  76111. if (width < 8 || width > 0x7fff) {
  76112. throw "HDR Bad header format, unsupported size";
  76113. }
  76114. lineIndex += (line.length + 1);
  76115. return {
  76116. height: height,
  76117. width: width,
  76118. dataPosition: lineIndex
  76119. };
  76120. };
  76121. /**
  76122. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  76123. * This RGBE texture needs to store the information as a panorama.
  76124. *
  76125. * More information on this format are available here:
  76126. * https://en.wikipedia.org/wiki/RGBE_image_format
  76127. *
  76128. * @param buffer The binary file stored in an array buffer.
  76129. * @param size The expected size of the extracted cubemap.
  76130. * @return The Cube Map information.
  76131. */
  76132. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  76133. var uint8array = new Uint8Array(buffer);
  76134. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  76135. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  76136. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  76137. return cubeMapData;
  76138. };
  76139. /**
  76140. * Returns the pixels data extracted from an RGBE texture.
  76141. * This pixels will be stored left to right up to down in the R G B order in one array.
  76142. *
  76143. * More information on this format are available here:
  76144. * https://en.wikipedia.org/wiki/RGBE_image_format
  76145. *
  76146. * @param uint8array The binary file stored in an array buffer.
  76147. * @param hdrInfo The header information of the file.
  76148. * @return The pixels data in RGB right to left up to down order.
  76149. */
  76150. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  76151. // Keep for multi format supports.
  76152. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  76153. };
  76154. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  76155. var num_scanlines = hdrInfo.height;
  76156. var scanline_width = hdrInfo.width;
  76157. var a, b, c, d, count;
  76158. var dataIndex = hdrInfo.dataPosition;
  76159. var index = 0, endIndex = 0, i = 0;
  76160. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  76161. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  76162. // 3 channels of 4 bytes per pixel in float.
  76163. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  76164. var resultArray = new Float32Array(resultBuffer);
  76165. // read in each successive scanline
  76166. while (num_scanlines > 0) {
  76167. a = uint8array[dataIndex++];
  76168. b = uint8array[dataIndex++];
  76169. c = uint8array[dataIndex++];
  76170. d = uint8array[dataIndex++];
  76171. if (a != 2 || b != 2 || (c & 0x80)) {
  76172. // this file is not run length encoded
  76173. throw "HDR Bad header format, not RLE";
  76174. }
  76175. if (((c << 8) | d) != scanline_width) {
  76176. throw "HDR Bad header format, wrong scan line width";
  76177. }
  76178. index = 0;
  76179. // read each of the four channels for the scanline into the buffer
  76180. for (i = 0; i < 4; i++) {
  76181. endIndex = (i + 1) * scanline_width;
  76182. while (index < endIndex) {
  76183. a = uint8array[dataIndex++];
  76184. b = uint8array[dataIndex++];
  76185. if (a > 128) {
  76186. // a run of the same value
  76187. count = a - 128;
  76188. if ((count == 0) || (count > endIndex - index)) {
  76189. throw "HDR Bad Format, bad scanline data (run)";
  76190. }
  76191. while (count-- > 0) {
  76192. scanLineArray[index++] = b;
  76193. }
  76194. }
  76195. else {
  76196. // a non-run
  76197. count = a;
  76198. if ((count == 0) || (count > endIndex - index)) {
  76199. throw "HDR Bad Format, bad scanline data (non-run)";
  76200. }
  76201. scanLineArray[index++] = b;
  76202. if (--count > 0) {
  76203. for (var j = 0; j < count; j++) {
  76204. scanLineArray[index++] = uint8array[dataIndex++];
  76205. }
  76206. }
  76207. }
  76208. }
  76209. }
  76210. // now convert data from buffer into floats
  76211. for (i = 0; i < scanline_width; i++) {
  76212. a = scanLineArray[i];
  76213. b = scanLineArray[i + scanline_width];
  76214. c = scanLineArray[i + 2 * scanline_width];
  76215. d = scanLineArray[i + 3 * scanline_width];
  76216. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  76217. }
  76218. num_scanlines--;
  76219. }
  76220. return resultArray;
  76221. };
  76222. return HDRTools;
  76223. }());
  76224. BABYLON.HDRTools = HDRTools;
  76225. })(BABYLON || (BABYLON = {}));
  76226. //# sourceMappingURL=babylon.hdr.js.map
  76227. "use strict";
  76228. var BABYLON;
  76229. (function (BABYLON) {
  76230. /**
  76231. * This represents a texture coming from an HDR input.
  76232. *
  76233. * The only supported format is currently panorama picture stored in RGBE format.
  76234. * Example of such files can be found on HDRLib: http://hdrlib.com/
  76235. */
  76236. var HDRCubeTexture = /** @class */ (function (_super) {
  76237. __extends(HDRCubeTexture, _super);
  76238. /**
  76239. * Instantiates an HDRTexture from the following parameters.
  76240. *
  76241. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  76242. * @param scene The scene the texture will be used in
  76243. * @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.
  76244. * @param noMipmap Forces to not generate the mipmap if true
  76245. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  76246. * @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)
  76247. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  76248. */
  76249. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  76250. if (noMipmap === void 0) { noMipmap = false; }
  76251. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76252. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76253. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76254. if (onLoad === void 0) { onLoad = null; }
  76255. if (onError === void 0) { onError = null; }
  76256. var _this = _super.call(this, scene) || this;
  76257. _this._useInGammaSpace = false;
  76258. _this._generateHarmonics = true;
  76259. _this._isBABYLONPreprocessed = false;
  76260. _this._onLoad = null;
  76261. _this._onError = null;
  76262. /**
  76263. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  76264. */
  76265. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  76266. /**
  76267. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  76268. * This is usefull at run time to apply the good shader.
  76269. */
  76270. _this.isPMREM = false;
  76271. _this._isBlocking = true;
  76272. /**
  76273. * Gets or sets the center of the bounding box associated with the cube texture
  76274. * It must define where the camera used to render the texture was set
  76275. */
  76276. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  76277. if (!url) {
  76278. return _this;
  76279. }
  76280. _this.name = url;
  76281. _this.url = url;
  76282. _this.hasAlpha = false;
  76283. _this.isCube = true;
  76284. _this._textureMatrix = BABYLON.Matrix.Identity();
  76285. _this._onLoad = onLoad;
  76286. _this._onError = onError;
  76287. _this.gammaSpace = false;
  76288. var caps = scene.getEngine().getCaps();
  76289. if (size) {
  76290. _this._isBABYLONPreprocessed = false;
  76291. _this._noMipmap = noMipmap;
  76292. _this._size = size;
  76293. _this._useInGammaSpace = useInGammaSpace;
  76294. _this._usePMREMGenerator = usePMREMGenerator &&
  76295. caps.textureLOD &&
  76296. caps.textureFloat &&
  76297. !_this._useInGammaSpace;
  76298. }
  76299. else {
  76300. _this._isBABYLONPreprocessed = true;
  76301. _this._noMipmap = false;
  76302. _this._useInGammaSpace = false;
  76303. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  76304. !_this._useInGammaSpace;
  76305. }
  76306. _this.isPMREM = _this._usePMREMGenerator;
  76307. _this._texture = _this._getFromCache(url, _this._noMipmap);
  76308. if (!_this._texture) {
  76309. if (!scene.useDelayedTextureLoading) {
  76310. _this.loadTexture();
  76311. }
  76312. else {
  76313. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  76314. }
  76315. }
  76316. return _this;
  76317. }
  76318. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  76319. /**
  76320. * Gets wether or not the texture is blocking during loading.
  76321. */
  76322. get: function () {
  76323. return this._isBlocking;
  76324. },
  76325. /**
  76326. * Sets wether or not the texture is blocking during loading.
  76327. */
  76328. set: function (value) {
  76329. this._isBlocking = value;
  76330. },
  76331. enumerable: true,
  76332. configurable: true
  76333. });
  76334. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  76335. get: function () {
  76336. return this._boundingBoxSize;
  76337. },
  76338. /**
  76339. * Gets or sets the size of the bounding box associated with the cube texture
  76340. * When defined, the cubemap will switch to local mode
  76341. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  76342. * @example https://www.babylonjs-playground.com/#RNASML
  76343. */
  76344. set: function (value) {
  76345. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  76346. return;
  76347. }
  76348. this._boundingBoxSize = value;
  76349. var scene = this.getScene();
  76350. if (scene) {
  76351. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  76352. }
  76353. },
  76354. enumerable: true,
  76355. configurable: true
  76356. });
  76357. /**
  76358. * Occurs when the file is a preprocessed .babylon.hdr file.
  76359. */
  76360. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  76361. var _this = this;
  76362. var mipLevels = 0;
  76363. var floatArrayView = null;
  76364. var scene = this.getScene();
  76365. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  76366. var mips = new Array();
  76367. if (!floatArrayView) {
  76368. return mips;
  76369. }
  76370. var startIndex = 30;
  76371. for (var level = 0; level < mipLevels; level++) {
  76372. mips.push([]);
  76373. // Fill each pixel of the mip level.
  76374. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  76375. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  76376. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  76377. mips[level].push(faceData);
  76378. startIndex += faceSize;
  76379. }
  76380. }
  76381. return mips;
  76382. } : null;
  76383. var callback = function (buffer) {
  76384. var scene = _this.getScene();
  76385. if (!scene) {
  76386. return null;
  76387. }
  76388. // Create Native Array Views
  76389. var intArrayView = new Int32Array(buffer);
  76390. floatArrayView = new Float32Array(buffer);
  76391. // Fill header.
  76392. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  76393. _this._size = intArrayView[1]; // CubeMap max mip face size.
  76394. // Update Texture Information.
  76395. if (!_this._texture) {
  76396. return null;
  76397. }
  76398. _this._texture.updateSize(_this._size, _this._size);
  76399. // Fill polynomial information.
  76400. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  76401. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  76402. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  76403. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  76404. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  76405. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  76406. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  76407. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  76408. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  76409. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  76410. _this.sphericalPolynomial = sphericalPolynomial;
  76411. // Fill pixel data.
  76412. mipLevels = intArrayView[29]; // Number of mip levels.
  76413. var startIndex = 30;
  76414. var data = [];
  76415. var faceSize = Math.pow(_this._size, 2) * 3;
  76416. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  76417. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  76418. startIndex += faceSize;
  76419. }
  76420. var results = [];
  76421. var byteArray = null;
  76422. // Push each faces.
  76423. for (var k = 0; k < 6; k++) {
  76424. var dataFace = null;
  76425. // To be deprecated.
  76426. if (version === 1) {
  76427. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  76428. dataFace = data[j];
  76429. }
  76430. // If special cases.
  76431. if (!mipmapGenerator && dataFace) {
  76432. if (!scene.getEngine().getCaps().textureFloat) {
  76433. // 3 channels of 1 bytes per pixel in bytes.
  76434. var byteBuffer = new ArrayBuffer(faceSize);
  76435. byteArray = new Uint8Array(byteBuffer);
  76436. }
  76437. for (var i = 0; i < _this._size * _this._size; i++) {
  76438. // Put in gamma space if requested.
  76439. if (_this._useInGammaSpace) {
  76440. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  76441. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  76442. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  76443. }
  76444. // Convert to int texture for fallback.
  76445. if (byteArray) {
  76446. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  76447. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  76448. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  76449. // May use luminance instead if the result is not accurate.
  76450. var max = Math.max(Math.max(r, g), b);
  76451. if (max > 255) {
  76452. var scale = 255 / max;
  76453. r *= scale;
  76454. g *= scale;
  76455. b *= scale;
  76456. }
  76457. byteArray[(i * 3) + 0] = r;
  76458. byteArray[(i * 3) + 1] = g;
  76459. byteArray[(i * 3) + 2] = b;
  76460. }
  76461. }
  76462. }
  76463. // Fill the array accordingly.
  76464. if (byteArray) {
  76465. results.push(byteArray);
  76466. }
  76467. else {
  76468. results.push(dataFace);
  76469. }
  76470. }
  76471. return results;
  76472. };
  76473. if (scene) {
  76474. 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);
  76475. }
  76476. };
  76477. /**
  76478. * Occurs when the file is raw .hdr file.
  76479. */
  76480. HDRCubeTexture.prototype.loadHDRTexture = function () {
  76481. var _this = this;
  76482. var callback = function (buffer) {
  76483. var scene = _this.getScene();
  76484. if (!scene) {
  76485. return null;
  76486. }
  76487. // Extract the raw linear data.
  76488. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  76489. // Generate harmonics if needed.
  76490. if (_this._generateHarmonics) {
  76491. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  76492. _this.sphericalPolynomial = sphericalPolynomial;
  76493. }
  76494. var results = [];
  76495. var byteArray = null;
  76496. // Push each faces.
  76497. for (var j = 0; j < 6; j++) {
  76498. // Create uintarray fallback.
  76499. if (!scene.getEngine().getCaps().textureFloat) {
  76500. // 3 channels of 1 bytes per pixel in bytes.
  76501. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  76502. byteArray = new Uint8Array(byteBuffer);
  76503. }
  76504. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  76505. // If special cases.
  76506. if (_this._useInGammaSpace || byteArray) {
  76507. for (var i = 0; i < _this._size * _this._size; i++) {
  76508. // Put in gamma space if requested.
  76509. if (_this._useInGammaSpace) {
  76510. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  76511. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  76512. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  76513. }
  76514. // Convert to int texture for fallback.
  76515. if (byteArray) {
  76516. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  76517. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  76518. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  76519. // May use luminance instead if the result is not accurate.
  76520. var max = Math.max(Math.max(r, g), b);
  76521. if (max > 255) {
  76522. var scale = 255 / max;
  76523. r *= scale;
  76524. g *= scale;
  76525. b *= scale;
  76526. }
  76527. byteArray[(i * 3) + 0] = r;
  76528. byteArray[(i * 3) + 1] = g;
  76529. byteArray[(i * 3) + 2] = b;
  76530. }
  76531. }
  76532. }
  76533. if (byteArray) {
  76534. results.push(byteArray);
  76535. }
  76536. else {
  76537. results.push(dataFace);
  76538. }
  76539. }
  76540. return results;
  76541. };
  76542. var mipmapGenerator = null;
  76543. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  76544. // if (!this._noMipmap &&
  76545. // this._usePMREMGenerator) {
  76546. // mipmapGenerator = (data: ArrayBufferView[]) => {
  76547. // // Custom setup of the generator matching with the PBR shader values.
  76548. // var generator = new BABYLON.PMREMGenerator(data,
  76549. // this._size,
  76550. // this._size,
  76551. // 0,
  76552. // 3,
  76553. // this.getScene().getEngine().getCaps().textureFloat,
  76554. // 2048,
  76555. // 0.25,
  76556. // false,
  76557. // true);
  76558. // return generator.filterCubeMap();
  76559. // };
  76560. // }
  76561. var scene = this.getScene();
  76562. if (scene) {
  76563. 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);
  76564. }
  76565. };
  76566. /**
  76567. * Starts the loading process of the texture.
  76568. */
  76569. HDRCubeTexture.prototype.loadTexture = function () {
  76570. if (this._isBABYLONPreprocessed) {
  76571. this.loadBabylonTexture();
  76572. }
  76573. else {
  76574. this.loadHDRTexture();
  76575. }
  76576. };
  76577. HDRCubeTexture.prototype.clone = function () {
  76578. var scene = this.getScene();
  76579. if (!scene) {
  76580. return this;
  76581. }
  76582. var size = (this._isBABYLONPreprocessed ? null : this._size);
  76583. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  76584. // Base texture
  76585. newTexture.level = this.level;
  76586. newTexture.wrapU = this.wrapU;
  76587. newTexture.wrapV = this.wrapV;
  76588. newTexture.coordinatesIndex = this.coordinatesIndex;
  76589. newTexture.coordinatesMode = this.coordinatesMode;
  76590. return newTexture;
  76591. };
  76592. // Methods
  76593. HDRCubeTexture.prototype.delayLoad = function () {
  76594. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  76595. return;
  76596. }
  76597. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  76598. this._texture = this._getFromCache(this.url, this._noMipmap);
  76599. if (!this._texture) {
  76600. this.loadTexture();
  76601. }
  76602. };
  76603. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  76604. return this._textureMatrix;
  76605. };
  76606. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  76607. this._textureMatrix = value;
  76608. };
  76609. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  76610. var texture = null;
  76611. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  76612. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  76613. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  76614. texture.name = parsedTexture.name;
  76615. texture.hasAlpha = parsedTexture.hasAlpha;
  76616. texture.level = parsedTexture.level;
  76617. texture.coordinatesMode = parsedTexture.coordinatesMode;
  76618. texture.isBlocking = parsedTexture.isBlocking;
  76619. }
  76620. if (texture) {
  76621. if (parsedTexture.boundingBoxPosition) {
  76622. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  76623. }
  76624. if (parsedTexture.boundingBoxSize) {
  76625. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  76626. }
  76627. }
  76628. return texture;
  76629. };
  76630. HDRCubeTexture.prototype.serialize = function () {
  76631. if (!this.name) {
  76632. return null;
  76633. }
  76634. var serializationObject = {};
  76635. serializationObject.name = this.name;
  76636. serializationObject.hasAlpha = this.hasAlpha;
  76637. serializationObject.isCube = true;
  76638. serializationObject.level = this.level;
  76639. serializationObject.size = this._size;
  76640. serializationObject.coordinatesMode = this.coordinatesMode;
  76641. serializationObject.useInGammaSpace = this._useInGammaSpace;
  76642. serializationObject.generateHarmonics = this._generateHarmonics;
  76643. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  76644. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  76645. serializationObject.customType = "BABYLON.HDRCubeTexture";
  76646. serializationObject.noMipmap = this._noMipmap;
  76647. serializationObject.isBlocking = this._isBlocking;
  76648. return serializationObject;
  76649. };
  76650. /**
  76651. * Saves as a file the data contained in the texture in a binary format.
  76652. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  76653. * as the spherical used in the lighting.
  76654. * @param url The HDR file url.
  76655. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  76656. * @param onError Method called if any error happens during download.
  76657. * @return The packed binary data.
  76658. */
  76659. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  76660. if (onError === void 0) { onError = null; }
  76661. var callback = function (buffer) {
  76662. var data = new Blob([buffer], { type: 'application/octet-stream' });
  76663. // Returns a URL you can use as a href.
  76664. var objUrl = window.URL.createObjectURL(data);
  76665. // Simulates a link to it and click to dowload.
  76666. var a = document.createElement("a");
  76667. document.body.appendChild(a);
  76668. a.style.display = "none";
  76669. a.href = objUrl;
  76670. a.download = "envmap.babylon.hdr";
  76671. a.click();
  76672. };
  76673. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  76674. };
  76675. /**
  76676. * Serializes the data contained in the texture in a binary format.
  76677. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  76678. * as the spherical used in the lighting.
  76679. * @param url The HDR file url.
  76680. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  76681. * @param onError Method called if any error happens during download.
  76682. * @return The packed binary data.
  76683. */
  76684. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  76685. if (onError === void 0) { onError = null; }
  76686. // Needs the url tho create the texture.
  76687. if (!url) {
  76688. return;
  76689. }
  76690. // Check Power of two size.
  76691. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  76692. return;
  76693. }
  76694. // Coming Back in 3.x.
  76695. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  76696. };
  76697. HDRCubeTexture._facesMapping = [
  76698. "right",
  76699. "left",
  76700. "up",
  76701. "down",
  76702. "front",
  76703. "back"
  76704. ];
  76705. return HDRCubeTexture;
  76706. }(BABYLON.BaseTexture));
  76707. BABYLON.HDRCubeTexture = HDRCubeTexture;
  76708. })(BABYLON || (BABYLON = {}));
  76709. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  76710. "use strict";
  76711. var BABYLON;
  76712. (function (BABYLON) {
  76713. var IndexedVector2 = /** @class */ (function (_super) {
  76714. __extends(IndexedVector2, _super);
  76715. function IndexedVector2(original, index) {
  76716. var _this = _super.call(this, original.x, original.y) || this;
  76717. _this.index = index;
  76718. return _this;
  76719. }
  76720. return IndexedVector2;
  76721. }(BABYLON.Vector2));
  76722. var PolygonPoints = /** @class */ (function () {
  76723. function PolygonPoints() {
  76724. this.elements = new Array();
  76725. }
  76726. PolygonPoints.prototype.add = function (originalPoints) {
  76727. var _this = this;
  76728. var result = new Array();
  76729. originalPoints.forEach(function (point) {
  76730. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76731. var newPoint = new IndexedVector2(point, _this.elements.length);
  76732. result.push(newPoint);
  76733. _this.elements.push(newPoint);
  76734. }
  76735. });
  76736. return result;
  76737. };
  76738. PolygonPoints.prototype.computeBounds = function () {
  76739. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76740. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76741. this.elements.forEach(function (point) {
  76742. // x
  76743. if (point.x < lmin.x) {
  76744. lmin.x = point.x;
  76745. }
  76746. else if (point.x > lmax.x) {
  76747. lmax.x = point.x;
  76748. }
  76749. // y
  76750. if (point.y < lmin.y) {
  76751. lmin.y = point.y;
  76752. }
  76753. else if (point.y > lmax.y) {
  76754. lmax.y = point.y;
  76755. }
  76756. });
  76757. return {
  76758. min: lmin,
  76759. max: lmax,
  76760. width: lmax.x - lmin.x,
  76761. height: lmax.y - lmin.y
  76762. };
  76763. };
  76764. return PolygonPoints;
  76765. }());
  76766. var Polygon = /** @class */ (function () {
  76767. function Polygon() {
  76768. }
  76769. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76770. return [
  76771. new BABYLON.Vector2(xmin, ymin),
  76772. new BABYLON.Vector2(xmax, ymin),
  76773. new BABYLON.Vector2(xmax, ymax),
  76774. new BABYLON.Vector2(xmin, ymax)
  76775. ];
  76776. };
  76777. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76778. if (cx === void 0) { cx = 0; }
  76779. if (cy === void 0) { cy = 0; }
  76780. if (numberOfSides === void 0) { numberOfSides = 32; }
  76781. var result = new Array();
  76782. var angle = 0;
  76783. var increment = (Math.PI * 2) / numberOfSides;
  76784. for (var i = 0; i < numberOfSides; i++) {
  76785. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76786. angle -= increment;
  76787. }
  76788. return result;
  76789. };
  76790. Polygon.Parse = function (input) {
  76791. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76792. var i, result = [];
  76793. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76794. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76795. }
  76796. return result;
  76797. };
  76798. Polygon.StartingAt = function (x, y) {
  76799. return BABYLON.Path2.StartingAt(x, y);
  76800. };
  76801. return Polygon;
  76802. }());
  76803. BABYLON.Polygon = Polygon;
  76804. var PolygonMeshBuilder = /** @class */ (function () {
  76805. function PolygonMeshBuilder(name, contours, scene) {
  76806. this._points = new PolygonPoints();
  76807. this._outlinepoints = new PolygonPoints();
  76808. this._holes = new Array();
  76809. this._epoints = new Array();
  76810. this._eholes = new Array();
  76811. this._name = name;
  76812. this._scene = scene;
  76813. var points;
  76814. if (contours instanceof BABYLON.Path2) {
  76815. points = contours.getPoints();
  76816. }
  76817. else {
  76818. points = contours;
  76819. }
  76820. this._addToepoint(points);
  76821. this._points.add(points);
  76822. this._outlinepoints.add(points);
  76823. if (typeof earcut === 'undefined') {
  76824. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  76825. }
  76826. }
  76827. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76828. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76829. var p = points_1[_i];
  76830. this._epoints.push(p.x, p.y);
  76831. }
  76832. };
  76833. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76834. this._points.add(hole);
  76835. var holepoints = new PolygonPoints();
  76836. holepoints.add(hole);
  76837. this._holes.push(holepoints);
  76838. this._eholes.push(this._epoints.length / 2);
  76839. this._addToepoint(hole);
  76840. return this;
  76841. };
  76842. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76843. var _this = this;
  76844. if (updatable === void 0) { updatable = false; }
  76845. if (depth === void 0) { depth = 0; }
  76846. var result = new BABYLON.Mesh(this._name, this._scene);
  76847. var normals = new Array();
  76848. var positions = new Array();
  76849. var uvs = new Array();
  76850. var bounds = this._points.computeBounds();
  76851. this._points.elements.forEach(function (p) {
  76852. normals.push(0, 1.0, 0);
  76853. positions.push(p.x, 0, p.y);
  76854. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76855. });
  76856. var indices = new Array();
  76857. var res = earcut(this._epoints, this._eholes, 2);
  76858. for (var i = 0; i < res.length; i++) {
  76859. indices.push(res[i]);
  76860. }
  76861. if (depth > 0) {
  76862. var positionscount = (positions.length / 3); //get the current pointcount
  76863. this._points.elements.forEach(function (p) {
  76864. normals.push(0, -1.0, 0);
  76865. positions.push(p.x, -depth, p.y);
  76866. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76867. });
  76868. var totalCount = indices.length;
  76869. for (var i = 0; i < totalCount; i += 3) {
  76870. var i0 = indices[i + 0];
  76871. var i1 = indices[i + 1];
  76872. var i2 = indices[i + 2];
  76873. indices.push(i2 + positionscount);
  76874. indices.push(i1 + positionscount);
  76875. indices.push(i0 + positionscount);
  76876. }
  76877. //Add the sides
  76878. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76879. this._holes.forEach(function (hole) {
  76880. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76881. });
  76882. }
  76883. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76884. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76885. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76886. result.setIndices(indices);
  76887. return result;
  76888. };
  76889. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76890. var StartIndex = positions.length / 3;
  76891. var ulength = 0;
  76892. for (var i = 0; i < points.elements.length; i++) {
  76893. var p = points.elements[i];
  76894. var p1;
  76895. if ((i + 1) > points.elements.length - 1) {
  76896. p1 = points.elements[0];
  76897. }
  76898. else {
  76899. p1 = points.elements[i + 1];
  76900. }
  76901. positions.push(p.x, 0, p.y);
  76902. positions.push(p.x, -depth, p.y);
  76903. positions.push(p1.x, 0, p1.y);
  76904. positions.push(p1.x, -depth, p1.y);
  76905. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76906. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76907. var v3 = v2.subtract(v1);
  76908. var v4 = new BABYLON.Vector3(0, 1, 0);
  76909. var vn = BABYLON.Vector3.Cross(v3, v4);
  76910. vn = vn.normalize();
  76911. uvs.push(ulength / bounds.width, 0);
  76912. uvs.push(ulength / bounds.width, 1);
  76913. ulength += v3.length();
  76914. uvs.push((ulength / bounds.width), 0);
  76915. uvs.push((ulength / bounds.width), 1);
  76916. if (!flip) {
  76917. normals.push(-vn.x, -vn.y, -vn.z);
  76918. normals.push(-vn.x, -vn.y, -vn.z);
  76919. normals.push(-vn.x, -vn.y, -vn.z);
  76920. normals.push(-vn.x, -vn.y, -vn.z);
  76921. indices.push(StartIndex);
  76922. indices.push(StartIndex + 1);
  76923. indices.push(StartIndex + 2);
  76924. indices.push(StartIndex + 1);
  76925. indices.push(StartIndex + 3);
  76926. indices.push(StartIndex + 2);
  76927. }
  76928. else {
  76929. normals.push(vn.x, vn.y, vn.z);
  76930. normals.push(vn.x, vn.y, vn.z);
  76931. normals.push(vn.x, vn.y, vn.z);
  76932. normals.push(vn.x, vn.y, vn.z);
  76933. indices.push(StartIndex);
  76934. indices.push(StartIndex + 2);
  76935. indices.push(StartIndex + 1);
  76936. indices.push(StartIndex + 1);
  76937. indices.push(StartIndex + 2);
  76938. indices.push(StartIndex + 3);
  76939. }
  76940. StartIndex += 4;
  76941. }
  76942. ;
  76943. };
  76944. return PolygonMeshBuilder;
  76945. }());
  76946. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76947. })(BABYLON || (BABYLON = {}));
  76948. //# sourceMappingURL=babylon.polygonMesh.js.map
  76949. "use strict";
  76950. var BABYLON;
  76951. (function (BABYLON) {
  76952. // Unique ID when we import meshes from Babylon to CSG
  76953. var currentCSGMeshId = 0;
  76954. // # class Vertex
  76955. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76956. // one to provide additional features like texture coordinates and vertex
  76957. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76958. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76959. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76960. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76961. // is not used anywhere else.
  76962. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76963. var Vertex = /** @class */ (function () {
  76964. function Vertex(pos, normal, uv) {
  76965. this.pos = pos;
  76966. this.normal = normal;
  76967. this.uv = uv;
  76968. }
  76969. Vertex.prototype.clone = function () {
  76970. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76971. };
  76972. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76973. // orientation of a polygon is flipped.
  76974. Vertex.prototype.flip = function () {
  76975. this.normal = this.normal.scale(-1);
  76976. };
  76977. // Create a new vertex between this vertex and `other` by linearly
  76978. // interpolating all properties using a parameter of `t`. Subclasses should
  76979. // override this to interpolate additional properties.
  76980. Vertex.prototype.interpolate = function (other, t) {
  76981. 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));
  76982. };
  76983. return Vertex;
  76984. }());
  76985. // # class Plane
  76986. // Represents a plane in 3D space.
  76987. var Plane = /** @class */ (function () {
  76988. function Plane(normal, w) {
  76989. this.normal = normal;
  76990. this.w = w;
  76991. }
  76992. Plane.FromPoints = function (a, b, c) {
  76993. var v0 = c.subtract(a);
  76994. var v1 = b.subtract(a);
  76995. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76996. return null;
  76997. }
  76998. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76999. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  77000. };
  77001. Plane.prototype.clone = function () {
  77002. return new Plane(this.normal.clone(), this.w);
  77003. };
  77004. Plane.prototype.flip = function () {
  77005. this.normal.scaleInPlace(-1);
  77006. this.w = -this.w;
  77007. };
  77008. // Split `polygon` by this plane if needed, then put the polygon or polygon
  77009. // fragments in the appropriate lists. Coplanar polygons go into either
  77010. // `coplanarFront` or `coplanarBack` depending on their orientation with
  77011. // respect to this plane. Polygons in front or in back of this plane go into
  77012. // either `front` or `back`.
  77013. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  77014. var COPLANAR = 0;
  77015. var FRONT = 1;
  77016. var BACK = 2;
  77017. var SPANNING = 3;
  77018. // Classify each point as well as the entire polygon into one of the above
  77019. // four classes.
  77020. var polygonType = 0;
  77021. var types = [];
  77022. var i;
  77023. var t;
  77024. for (i = 0; i < polygon.vertices.length; i++) {
  77025. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  77026. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  77027. polygonType |= type;
  77028. types.push(type);
  77029. }
  77030. // Put the polygon in the correct list, splitting it when necessary.
  77031. switch (polygonType) {
  77032. case COPLANAR:
  77033. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  77034. break;
  77035. case FRONT:
  77036. front.push(polygon);
  77037. break;
  77038. case BACK:
  77039. back.push(polygon);
  77040. break;
  77041. case SPANNING:
  77042. var f = [], b = [];
  77043. for (i = 0; i < polygon.vertices.length; i++) {
  77044. var j = (i + 1) % polygon.vertices.length;
  77045. var ti = types[i], tj = types[j];
  77046. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  77047. if (ti !== BACK)
  77048. f.push(vi);
  77049. if (ti !== FRONT)
  77050. b.push(ti !== BACK ? vi.clone() : vi);
  77051. if ((ti | tj) === SPANNING) {
  77052. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  77053. var v = vi.interpolate(vj, t);
  77054. f.push(v);
  77055. b.push(v.clone());
  77056. }
  77057. }
  77058. var poly;
  77059. if (f.length >= 3) {
  77060. poly = new Polygon(f, polygon.shared);
  77061. if (poly.plane)
  77062. front.push(poly);
  77063. }
  77064. if (b.length >= 3) {
  77065. poly = new Polygon(b, polygon.shared);
  77066. if (poly.plane)
  77067. back.push(poly);
  77068. }
  77069. break;
  77070. }
  77071. };
  77072. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  77073. // point is on the plane.
  77074. Plane.EPSILON = 1e-5;
  77075. return Plane;
  77076. }());
  77077. // # class Polygon
  77078. // Represents a convex polygon. The vertices used to initialize a polygon must
  77079. // be coplanar and form a convex loop.
  77080. //
  77081. // Each convex polygon has a `shared` property, which is shared between all
  77082. // polygons that are clones of each other or were split from the same polygon.
  77083. // This can be used to define per-polygon properties (such as surface color).
  77084. var Polygon = /** @class */ (function () {
  77085. function Polygon(vertices, shared) {
  77086. this.vertices = vertices;
  77087. this.shared = shared;
  77088. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  77089. }
  77090. Polygon.prototype.clone = function () {
  77091. var vertices = this.vertices.map(function (v) { return v.clone(); });
  77092. return new Polygon(vertices, this.shared);
  77093. };
  77094. Polygon.prototype.flip = function () {
  77095. this.vertices.reverse().map(function (v) { v.flip(); });
  77096. this.plane.flip();
  77097. };
  77098. return Polygon;
  77099. }());
  77100. // # class Node
  77101. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  77102. // by picking a polygon to split along. That polygon (and all other coplanar
  77103. // polygons) are added directly to that node and the other polygons are added to
  77104. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  77105. // no distinction between internal and leaf nodes.
  77106. var Node = /** @class */ (function () {
  77107. function Node(polygons) {
  77108. this.plane = null;
  77109. this.front = null;
  77110. this.back = null;
  77111. this.polygons = new Array();
  77112. if (polygons) {
  77113. this.build(polygons);
  77114. }
  77115. }
  77116. Node.prototype.clone = function () {
  77117. var node = new Node();
  77118. node.plane = this.plane && this.plane.clone();
  77119. node.front = this.front && this.front.clone();
  77120. node.back = this.back && this.back.clone();
  77121. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  77122. return node;
  77123. };
  77124. // Convert solid space to empty space and empty space to solid space.
  77125. Node.prototype.invert = function () {
  77126. for (var i = 0; i < this.polygons.length; i++) {
  77127. this.polygons[i].flip();
  77128. }
  77129. if (this.plane) {
  77130. this.plane.flip();
  77131. }
  77132. if (this.front) {
  77133. this.front.invert();
  77134. }
  77135. if (this.back) {
  77136. this.back.invert();
  77137. }
  77138. var temp = this.front;
  77139. this.front = this.back;
  77140. this.back = temp;
  77141. };
  77142. // Recursively remove all polygons in `polygons` that are inside this BSP
  77143. // tree.
  77144. Node.prototype.clipPolygons = function (polygons) {
  77145. if (!this.plane)
  77146. return polygons.slice();
  77147. var front = new Array(), back = new Array();
  77148. for (var i = 0; i < polygons.length; i++) {
  77149. this.plane.splitPolygon(polygons[i], front, back, front, back);
  77150. }
  77151. if (this.front) {
  77152. front = this.front.clipPolygons(front);
  77153. }
  77154. if (this.back) {
  77155. back = this.back.clipPolygons(back);
  77156. }
  77157. else {
  77158. back = [];
  77159. }
  77160. return front.concat(back);
  77161. };
  77162. // Remove all polygons in this BSP tree that are inside the other BSP tree
  77163. // `bsp`.
  77164. Node.prototype.clipTo = function (bsp) {
  77165. this.polygons = bsp.clipPolygons(this.polygons);
  77166. if (this.front)
  77167. this.front.clipTo(bsp);
  77168. if (this.back)
  77169. this.back.clipTo(bsp);
  77170. };
  77171. // Return a list of all polygons in this BSP tree.
  77172. Node.prototype.allPolygons = function () {
  77173. var polygons = this.polygons.slice();
  77174. if (this.front)
  77175. polygons = polygons.concat(this.front.allPolygons());
  77176. if (this.back)
  77177. polygons = polygons.concat(this.back.allPolygons());
  77178. return polygons;
  77179. };
  77180. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  77181. // new polygons are filtered down to the bottom of the tree and become new
  77182. // nodes there. Each set of polygons is partitioned using the first polygon
  77183. // (no heuristic is used to pick a good split).
  77184. Node.prototype.build = function (polygons) {
  77185. if (!polygons.length)
  77186. return;
  77187. if (!this.plane)
  77188. this.plane = polygons[0].plane.clone();
  77189. var front = new Array(), back = new Array();
  77190. for (var i = 0; i < polygons.length; i++) {
  77191. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  77192. }
  77193. if (front.length) {
  77194. if (!this.front)
  77195. this.front = new Node();
  77196. this.front.build(front);
  77197. }
  77198. if (back.length) {
  77199. if (!this.back)
  77200. this.back = new Node();
  77201. this.back.build(back);
  77202. }
  77203. };
  77204. return Node;
  77205. }());
  77206. var CSG = /** @class */ (function () {
  77207. function CSG() {
  77208. this.polygons = new Array();
  77209. }
  77210. // Convert BABYLON.Mesh to BABYLON.CSG
  77211. CSG.FromMesh = function (mesh) {
  77212. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  77213. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  77214. if (mesh instanceof BABYLON.Mesh) {
  77215. mesh.computeWorldMatrix(true);
  77216. matrix = mesh.getWorldMatrix();
  77217. meshPosition = mesh.position.clone();
  77218. meshRotation = mesh.rotation.clone();
  77219. if (mesh.rotationQuaternion) {
  77220. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  77221. }
  77222. meshScaling = mesh.scaling.clone();
  77223. }
  77224. else {
  77225. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  77226. }
  77227. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  77228. var subMeshes = mesh.subMeshes;
  77229. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  77230. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  77231. vertices = [];
  77232. for (var j = 0; j < 3; j++) {
  77233. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  77234. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  77235. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  77236. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  77237. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  77238. vertex = new Vertex(position, normal, uv);
  77239. vertices.push(vertex);
  77240. }
  77241. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  77242. // To handle the case of degenerated triangle
  77243. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  77244. if (polygon.plane)
  77245. polygons.push(polygon);
  77246. }
  77247. }
  77248. var csg = CSG.FromPolygons(polygons);
  77249. csg.matrix = matrix;
  77250. csg.position = meshPosition;
  77251. csg.rotation = meshRotation;
  77252. csg.scaling = meshScaling;
  77253. csg.rotationQuaternion = meshRotationQuaternion;
  77254. currentCSGMeshId++;
  77255. return csg;
  77256. };
  77257. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  77258. CSG.FromPolygons = function (polygons) {
  77259. var csg = new CSG();
  77260. csg.polygons = polygons;
  77261. return csg;
  77262. };
  77263. CSG.prototype.clone = function () {
  77264. var csg = new CSG();
  77265. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  77266. csg.copyTransformAttributes(this);
  77267. return csg;
  77268. };
  77269. CSG.prototype.union = function (csg) {
  77270. var a = new Node(this.clone().polygons);
  77271. var b = new Node(csg.clone().polygons);
  77272. a.clipTo(b);
  77273. b.clipTo(a);
  77274. b.invert();
  77275. b.clipTo(a);
  77276. b.invert();
  77277. a.build(b.allPolygons());
  77278. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  77279. };
  77280. CSG.prototype.unionInPlace = function (csg) {
  77281. var a = new Node(this.polygons);
  77282. var b = new Node(csg.polygons);
  77283. a.clipTo(b);
  77284. b.clipTo(a);
  77285. b.invert();
  77286. b.clipTo(a);
  77287. b.invert();
  77288. a.build(b.allPolygons());
  77289. this.polygons = a.allPolygons();
  77290. };
  77291. CSG.prototype.subtract = function (csg) {
  77292. var a = new Node(this.clone().polygons);
  77293. var b = new Node(csg.clone().polygons);
  77294. a.invert();
  77295. a.clipTo(b);
  77296. b.clipTo(a);
  77297. b.invert();
  77298. b.clipTo(a);
  77299. b.invert();
  77300. a.build(b.allPolygons());
  77301. a.invert();
  77302. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  77303. };
  77304. CSG.prototype.subtractInPlace = function (csg) {
  77305. var a = new Node(this.polygons);
  77306. var b = new Node(csg.polygons);
  77307. a.invert();
  77308. a.clipTo(b);
  77309. b.clipTo(a);
  77310. b.invert();
  77311. b.clipTo(a);
  77312. b.invert();
  77313. a.build(b.allPolygons());
  77314. a.invert();
  77315. this.polygons = a.allPolygons();
  77316. };
  77317. CSG.prototype.intersect = function (csg) {
  77318. var a = new Node(this.clone().polygons);
  77319. var b = new Node(csg.clone().polygons);
  77320. a.invert();
  77321. b.clipTo(a);
  77322. b.invert();
  77323. a.clipTo(b);
  77324. b.clipTo(a);
  77325. a.build(b.allPolygons());
  77326. a.invert();
  77327. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  77328. };
  77329. CSG.prototype.intersectInPlace = function (csg) {
  77330. var a = new Node(this.polygons);
  77331. var b = new Node(csg.polygons);
  77332. a.invert();
  77333. b.clipTo(a);
  77334. b.invert();
  77335. a.clipTo(b);
  77336. b.clipTo(a);
  77337. a.build(b.allPolygons());
  77338. a.invert();
  77339. this.polygons = a.allPolygons();
  77340. };
  77341. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  77342. // not modified.
  77343. CSG.prototype.inverse = function () {
  77344. var csg = this.clone();
  77345. csg.inverseInPlace();
  77346. return csg;
  77347. };
  77348. CSG.prototype.inverseInPlace = function () {
  77349. this.polygons.map(function (p) { p.flip(); });
  77350. };
  77351. // This is used to keep meshes transformations so they can be restored
  77352. // when we build back a Babylon Mesh
  77353. // NB : All CSG operations are performed in world coordinates
  77354. CSG.prototype.copyTransformAttributes = function (csg) {
  77355. this.matrix = csg.matrix;
  77356. this.position = csg.position;
  77357. this.rotation = csg.rotation;
  77358. this.scaling = csg.scaling;
  77359. this.rotationQuaternion = csg.rotationQuaternion;
  77360. return this;
  77361. };
  77362. // Build Raw mesh from CSG
  77363. // Coordinates here are in world space
  77364. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  77365. var matrix = this.matrix.clone();
  77366. matrix.invert();
  77367. 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;
  77368. if (keepSubMeshes) {
  77369. // Sort Polygons, since subMeshes are indices range
  77370. polygons.sort(function (a, b) {
  77371. if (a.shared.meshId === b.shared.meshId) {
  77372. return a.shared.subMeshId - b.shared.subMeshId;
  77373. }
  77374. else {
  77375. return a.shared.meshId - b.shared.meshId;
  77376. }
  77377. });
  77378. }
  77379. for (var i = 0, il = polygons.length; i < il; i++) {
  77380. polygon = polygons[i];
  77381. // Building SubMeshes
  77382. if (!subMesh_dict[polygon.shared.meshId]) {
  77383. subMesh_dict[polygon.shared.meshId] = {};
  77384. }
  77385. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  77386. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  77387. indexStart: +Infinity,
  77388. indexEnd: -Infinity,
  77389. materialIndex: polygon.shared.materialIndex
  77390. };
  77391. }
  77392. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  77393. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  77394. polygonIndices[0] = 0;
  77395. polygonIndices[1] = j - 1;
  77396. polygonIndices[2] = j;
  77397. for (var k = 0; k < 3; k++) {
  77398. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  77399. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  77400. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  77401. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  77402. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  77403. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  77404. // Check if 2 points can be merged
  77405. if (!(typeof vertex_idx !== 'undefined' &&
  77406. normals[vertex_idx * 3] === localNormal.x &&
  77407. normals[vertex_idx * 3 + 1] === localNormal.y &&
  77408. normals[vertex_idx * 3 + 2] === localNormal.z &&
  77409. uvs[vertex_idx * 2] === uv.x &&
  77410. uvs[vertex_idx * 2 + 1] === uv.y)) {
  77411. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  77412. uvs.push(uv.x, uv.y);
  77413. normals.push(normal.x, normal.y, normal.z);
  77414. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  77415. }
  77416. indices.push(vertex_idx);
  77417. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  77418. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  77419. currentIndex++;
  77420. }
  77421. }
  77422. }
  77423. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  77424. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  77425. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  77426. mesh.setIndices(indices, null);
  77427. if (keepSubMeshes) {
  77428. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  77429. var materialIndexOffset = 0, materialMaxIndex;
  77430. mesh.subMeshes = new Array();
  77431. for (var m in subMesh_dict) {
  77432. materialMaxIndex = -1;
  77433. for (var sm in subMesh_dict[m]) {
  77434. subMesh_obj = subMesh_dict[m][sm];
  77435. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  77436. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  77437. }
  77438. materialIndexOffset += ++materialMaxIndex;
  77439. }
  77440. }
  77441. return mesh;
  77442. };
  77443. // Build Mesh from CSG taking material and transforms into account
  77444. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  77445. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  77446. mesh.material = material;
  77447. mesh.position.copyFrom(this.position);
  77448. mesh.rotation.copyFrom(this.rotation);
  77449. if (this.rotationQuaternion) {
  77450. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  77451. }
  77452. mesh.scaling.copyFrom(this.scaling);
  77453. mesh.computeWorldMatrix(true);
  77454. return mesh;
  77455. };
  77456. return CSG;
  77457. }());
  77458. BABYLON.CSG = CSG;
  77459. })(BABYLON || (BABYLON = {}));
  77460. //# sourceMappingURL=babylon.csg.js.map
  77461. "use strict";
  77462. var BABYLON;
  77463. (function (BABYLON) {
  77464. var LensFlare = /** @class */ (function () {
  77465. function LensFlare(size, position, color, imgUrl, system) {
  77466. this.size = size;
  77467. this.position = position;
  77468. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77469. this.color = color || new BABYLON.Color3(1, 1, 1);
  77470. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  77471. this._system = system;
  77472. system.lensFlares.push(this);
  77473. }
  77474. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  77475. return new LensFlare(size, position, color, imgUrl, system);
  77476. };
  77477. LensFlare.prototype.dispose = function () {
  77478. if (this.texture) {
  77479. this.texture.dispose();
  77480. }
  77481. // Remove from scene
  77482. var index = this._system.lensFlares.indexOf(this);
  77483. this._system.lensFlares.splice(index, 1);
  77484. };
  77485. ;
  77486. return LensFlare;
  77487. }());
  77488. BABYLON.LensFlare = LensFlare;
  77489. })(BABYLON || (BABYLON = {}));
  77490. //# sourceMappingURL=babylon.lensFlare.js.map
  77491. "use strict";
  77492. var BABYLON;
  77493. (function (BABYLON) {
  77494. var LensFlareSystem = /** @class */ (function () {
  77495. function LensFlareSystem(name, emitter, scene) {
  77496. this.name = name;
  77497. this.lensFlares = new Array();
  77498. this.borderLimit = 300;
  77499. this.viewportBorder = 0;
  77500. this.layerMask = 0x0FFFFFFF;
  77501. this._vertexBuffers = {};
  77502. this._isEnabled = true;
  77503. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77504. this._emitter = emitter;
  77505. this.id = name;
  77506. scene.lensFlareSystems.push(this);
  77507. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  77508. var engine = scene.getEngine();
  77509. // VBO
  77510. var vertices = [];
  77511. vertices.push(1, 1);
  77512. vertices.push(-1, 1);
  77513. vertices.push(-1, -1);
  77514. vertices.push(1, -1);
  77515. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77516. // Indices
  77517. var indices = [];
  77518. indices.push(0);
  77519. indices.push(1);
  77520. indices.push(2);
  77521. indices.push(0);
  77522. indices.push(2);
  77523. indices.push(3);
  77524. this._indexBuffer = engine.createIndexBuffer(indices);
  77525. // Effects
  77526. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  77527. }
  77528. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  77529. get: function () {
  77530. return this._isEnabled;
  77531. },
  77532. set: function (value) {
  77533. this._isEnabled = value;
  77534. },
  77535. enumerable: true,
  77536. configurable: true
  77537. });
  77538. LensFlareSystem.prototype.getScene = function () {
  77539. return this._scene;
  77540. };
  77541. LensFlareSystem.prototype.getEmitter = function () {
  77542. return this._emitter;
  77543. };
  77544. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  77545. this._emitter = newEmitter;
  77546. };
  77547. LensFlareSystem.prototype.getEmitterPosition = function () {
  77548. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  77549. };
  77550. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  77551. var position = this.getEmitterPosition();
  77552. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  77553. this._positionX = position.x;
  77554. this._positionY = position.y;
  77555. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  77556. if (this.viewportBorder > 0) {
  77557. globalViewport.x -= this.viewportBorder;
  77558. globalViewport.y -= this.viewportBorder;
  77559. globalViewport.width += this.viewportBorder * 2;
  77560. globalViewport.height += this.viewportBorder * 2;
  77561. position.x += this.viewportBorder;
  77562. position.y += this.viewportBorder;
  77563. this._positionX += this.viewportBorder;
  77564. this._positionY += this.viewportBorder;
  77565. }
  77566. if (position.z > 0) {
  77567. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  77568. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  77569. return true;
  77570. }
  77571. return true;
  77572. }
  77573. return false;
  77574. };
  77575. LensFlareSystem.prototype._isVisible = function () {
  77576. if (!this._isEnabled || !this._scene.activeCamera) {
  77577. return false;
  77578. }
  77579. var emitterPosition = this.getEmitterPosition();
  77580. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  77581. var distance = direction.length();
  77582. direction.normalize();
  77583. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  77584. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  77585. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  77586. };
  77587. LensFlareSystem.prototype.render = function () {
  77588. if (!this._effect.isReady() || !this._scene.activeCamera)
  77589. return false;
  77590. var engine = this._scene.getEngine();
  77591. var viewport = this._scene.activeCamera.viewport;
  77592. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  77593. // Position
  77594. if (!this.computeEffectivePosition(globalViewport)) {
  77595. return false;
  77596. }
  77597. // Visibility
  77598. if (!this._isVisible()) {
  77599. return false;
  77600. }
  77601. // Intensity
  77602. var awayX;
  77603. var awayY;
  77604. if (this._positionX < this.borderLimit + globalViewport.x) {
  77605. awayX = this.borderLimit + globalViewport.x - this._positionX;
  77606. }
  77607. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  77608. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  77609. }
  77610. else {
  77611. awayX = 0;
  77612. }
  77613. if (this._positionY < this.borderLimit + globalViewport.y) {
  77614. awayY = this.borderLimit + globalViewport.y - this._positionY;
  77615. }
  77616. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  77617. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  77618. }
  77619. else {
  77620. awayY = 0;
  77621. }
  77622. var away = (awayX > awayY) ? awayX : awayY;
  77623. away -= this.viewportBorder;
  77624. if (away > this.borderLimit) {
  77625. away = this.borderLimit;
  77626. }
  77627. var intensity = 1.0 - (away / this.borderLimit);
  77628. if (intensity < 0) {
  77629. return false;
  77630. }
  77631. if (intensity > 1.0) {
  77632. intensity = 1.0;
  77633. }
  77634. if (this.viewportBorder > 0) {
  77635. globalViewport.x += this.viewportBorder;
  77636. globalViewport.y += this.viewportBorder;
  77637. globalViewport.width -= this.viewportBorder * 2;
  77638. globalViewport.height -= this.viewportBorder * 2;
  77639. this._positionX -= this.viewportBorder;
  77640. this._positionY -= this.viewportBorder;
  77641. }
  77642. // Position
  77643. var centerX = globalViewport.x + globalViewport.width / 2;
  77644. var centerY = globalViewport.y + globalViewport.height / 2;
  77645. var distX = centerX - this._positionX;
  77646. var distY = centerY - this._positionY;
  77647. // Effects
  77648. engine.enableEffect(this._effect);
  77649. engine.setState(false);
  77650. engine.setDepthBuffer(false);
  77651. // VBOs
  77652. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77653. // Flares
  77654. for (var index = 0; index < this.lensFlares.length; index++) {
  77655. var flare = this.lensFlares[index];
  77656. engine.setAlphaMode(flare.alphaMode);
  77657. var x = centerX - (distX * flare.position);
  77658. var y = centerY - (distY * flare.position);
  77659. var cw = flare.size;
  77660. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  77661. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  77662. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  77663. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  77664. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  77665. // Texture
  77666. this._effect.setTexture("textureSampler", flare.texture);
  77667. // Color
  77668. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  77669. // Draw order
  77670. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77671. }
  77672. engine.setDepthBuffer(true);
  77673. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77674. return true;
  77675. };
  77676. LensFlareSystem.prototype.dispose = function () {
  77677. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77678. if (vertexBuffer) {
  77679. vertexBuffer.dispose();
  77680. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77681. }
  77682. if (this._indexBuffer) {
  77683. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77684. this._indexBuffer = null;
  77685. }
  77686. while (this.lensFlares.length) {
  77687. this.lensFlares[0].dispose();
  77688. }
  77689. // Remove from scene
  77690. var index = this._scene.lensFlareSystems.indexOf(this);
  77691. this._scene.lensFlareSystems.splice(index, 1);
  77692. };
  77693. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  77694. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  77695. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  77696. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  77697. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  77698. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  77699. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  77700. var parsedFlare = parsedLensFlareSystem.flares[index];
  77701. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  77702. }
  77703. return lensFlareSystem;
  77704. };
  77705. LensFlareSystem.prototype.serialize = function () {
  77706. var serializationObject = {};
  77707. serializationObject.id = this.id;
  77708. serializationObject.name = this.name;
  77709. serializationObject.emitterId = this.getEmitter().id;
  77710. serializationObject.borderLimit = this.borderLimit;
  77711. serializationObject.flares = [];
  77712. for (var index = 0; index < this.lensFlares.length; index++) {
  77713. var flare = this.lensFlares[index];
  77714. serializationObject.flares.push({
  77715. size: flare.size,
  77716. position: flare.position,
  77717. color: flare.color.asArray(),
  77718. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  77719. });
  77720. }
  77721. return serializationObject;
  77722. };
  77723. return LensFlareSystem;
  77724. }());
  77725. BABYLON.LensFlareSystem = LensFlareSystem;
  77726. })(BABYLON || (BABYLON = {}));
  77727. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  77728. "use strict";
  77729. var BABYLON;
  77730. (function (BABYLON) {
  77731. /**
  77732. * This is a holder class for the physics joint created by the physics plugin.
  77733. * It holds a set of functions to control the underlying joint.
  77734. */
  77735. var PhysicsJoint = /** @class */ (function () {
  77736. function PhysicsJoint(type, jointData) {
  77737. this.type = type;
  77738. this.jointData = jointData;
  77739. jointData.nativeParams = jointData.nativeParams || {};
  77740. }
  77741. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77742. get: function () {
  77743. return this._physicsJoint;
  77744. },
  77745. set: function (newJoint) {
  77746. if (this._physicsJoint) {
  77747. //remove from the wolrd
  77748. }
  77749. this._physicsJoint = newJoint;
  77750. },
  77751. enumerable: true,
  77752. configurable: true
  77753. });
  77754. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77755. set: function (physicsPlugin) {
  77756. this._physicsPlugin = physicsPlugin;
  77757. },
  77758. enumerable: true,
  77759. configurable: true
  77760. });
  77761. /**
  77762. * Execute a function that is physics-plugin specific.
  77763. * @param {Function} func the function that will be executed.
  77764. * It accepts two parameters: the physics world and the physics joint.
  77765. */
  77766. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77767. func(this._physicsPlugin.world, this._physicsJoint);
  77768. };
  77769. //TODO check if the native joints are the same
  77770. //Joint Types
  77771. PhysicsJoint.DistanceJoint = 0;
  77772. PhysicsJoint.HingeJoint = 1;
  77773. PhysicsJoint.BallAndSocketJoint = 2;
  77774. PhysicsJoint.WheelJoint = 3;
  77775. PhysicsJoint.SliderJoint = 4;
  77776. //OIMO
  77777. PhysicsJoint.PrismaticJoint = 5;
  77778. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77779. PhysicsJoint.UniversalJoint = 6;
  77780. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77781. //Cannon
  77782. //Similar to a Ball-Joint. Different in params
  77783. PhysicsJoint.PointToPointJoint = 8;
  77784. //Cannon only at the moment
  77785. PhysicsJoint.SpringJoint = 9;
  77786. PhysicsJoint.LockJoint = 10;
  77787. return PhysicsJoint;
  77788. }());
  77789. BABYLON.PhysicsJoint = PhysicsJoint;
  77790. /**
  77791. * A class representing a physics distance joint.
  77792. */
  77793. var DistanceJoint = /** @class */ (function (_super) {
  77794. __extends(DistanceJoint, _super);
  77795. function DistanceJoint(jointData) {
  77796. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77797. }
  77798. /**
  77799. * Update the predefined distance.
  77800. */
  77801. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77802. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77803. };
  77804. return DistanceJoint;
  77805. }(PhysicsJoint));
  77806. BABYLON.DistanceJoint = DistanceJoint;
  77807. var MotorEnabledJoint = /** @class */ (function (_super) {
  77808. __extends(MotorEnabledJoint, _super);
  77809. function MotorEnabledJoint(type, jointData) {
  77810. return _super.call(this, type, jointData) || this;
  77811. }
  77812. /**
  77813. * Set the motor values.
  77814. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77815. * @param {number} force the force to apply
  77816. * @param {number} maxForce max force for this motor.
  77817. */
  77818. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77819. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77820. };
  77821. /**
  77822. * Set the motor's limits.
  77823. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77824. */
  77825. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77826. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77827. };
  77828. return MotorEnabledJoint;
  77829. }(PhysicsJoint));
  77830. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77831. /**
  77832. * This class represents a single hinge physics joint
  77833. */
  77834. var HingeJoint = /** @class */ (function (_super) {
  77835. __extends(HingeJoint, _super);
  77836. function HingeJoint(jointData) {
  77837. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77838. }
  77839. /**
  77840. * Set the motor values.
  77841. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77842. * @param {number} force the force to apply
  77843. * @param {number} maxForce max force for this motor.
  77844. */
  77845. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77846. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77847. };
  77848. /**
  77849. * Set the motor's limits.
  77850. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77851. */
  77852. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77853. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77854. };
  77855. return HingeJoint;
  77856. }(MotorEnabledJoint));
  77857. BABYLON.HingeJoint = HingeJoint;
  77858. /**
  77859. * This class represents a dual hinge physics joint (same as wheel joint)
  77860. */
  77861. var Hinge2Joint = /** @class */ (function (_super) {
  77862. __extends(Hinge2Joint, _super);
  77863. function Hinge2Joint(jointData) {
  77864. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77865. }
  77866. /**
  77867. * Set the motor values.
  77868. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77869. * @param {number} force the force to apply
  77870. * @param {number} maxForce max force for this motor.
  77871. * @param {motorIndex} the motor's index, 0 or 1.
  77872. */
  77873. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77874. if (motorIndex === void 0) { motorIndex = 0; }
  77875. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77876. };
  77877. /**
  77878. * Set the motor limits.
  77879. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77880. * @param {number} upperLimit the upper limit
  77881. * @param {number} lowerLimit lower limit
  77882. * @param {motorIndex} the motor's index, 0 or 1.
  77883. */
  77884. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77885. if (motorIndex === void 0) { motorIndex = 0; }
  77886. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77887. };
  77888. return Hinge2Joint;
  77889. }(MotorEnabledJoint));
  77890. BABYLON.Hinge2Joint = Hinge2Joint;
  77891. })(BABYLON || (BABYLON = {}));
  77892. //# sourceMappingURL=babylon.physicsJoint.js.map
  77893. "use strict";
  77894. var BABYLON;
  77895. (function (BABYLON) {
  77896. var PhysicsImpostor = /** @class */ (function () {
  77897. function PhysicsImpostor(object, type, _options, _scene) {
  77898. if (_options === void 0) { _options = { mass: 0 }; }
  77899. var _this = this;
  77900. this.object = object;
  77901. this.type = type;
  77902. this._options = _options;
  77903. this._scene = _scene;
  77904. this._bodyUpdateRequired = false;
  77905. this._onBeforePhysicsStepCallbacks = new Array();
  77906. this._onAfterPhysicsStepCallbacks = new Array();
  77907. this._onPhysicsCollideCallbacks = [];
  77908. this._deltaPosition = BABYLON.Vector3.Zero();
  77909. this._isDisposed = false;
  77910. //temp variables for parent rotation calculations
  77911. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77912. this._tmpQuat = new BABYLON.Quaternion();
  77913. this._tmpQuat2 = new BABYLON.Quaternion();
  77914. /**
  77915. * this function is executed by the physics engine.
  77916. */
  77917. this.beforeStep = function () {
  77918. if (!_this._physicsEngine) {
  77919. return;
  77920. }
  77921. _this.object.translate(_this._deltaPosition, -1);
  77922. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77923. _this.object.computeWorldMatrix(false);
  77924. if (_this.object.parent && _this.object.rotationQuaternion) {
  77925. _this.getParentsRotation();
  77926. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77927. }
  77928. else {
  77929. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77930. }
  77931. if (!_this._options.disableBidirectionalTransformation) {
  77932. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77933. }
  77934. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77935. func(_this);
  77936. });
  77937. };
  77938. /**
  77939. * this function is executed by the physics engine.
  77940. */
  77941. this.afterStep = function () {
  77942. if (!_this._physicsEngine) {
  77943. return;
  77944. }
  77945. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77946. func(_this);
  77947. });
  77948. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77949. // object has now its world rotation. needs to be converted to local.
  77950. if (_this.object.parent && _this.object.rotationQuaternion) {
  77951. _this.getParentsRotation();
  77952. _this._tmpQuat.conjugateInPlace();
  77953. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77954. }
  77955. // take the position set and make it the absolute position of this object.
  77956. _this.object.setAbsolutePosition(_this.object.position);
  77957. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77958. _this.object.translate(_this._deltaPosition, 1);
  77959. };
  77960. /**
  77961. * Legacy collision detection event support
  77962. */
  77963. this.onCollideEvent = null;
  77964. //event and body object due to cannon's event-based architecture.
  77965. this.onCollide = function (e) {
  77966. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77967. return;
  77968. }
  77969. if (!_this._physicsEngine) {
  77970. return;
  77971. }
  77972. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77973. if (otherImpostor) {
  77974. // Legacy collision detection event support
  77975. if (_this.onCollideEvent) {
  77976. _this.onCollideEvent(_this, otherImpostor);
  77977. }
  77978. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77979. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77980. }).forEach(function (obj) {
  77981. obj.callback(_this, otherImpostor);
  77982. });
  77983. }
  77984. };
  77985. //sanity check!
  77986. if (!this.object) {
  77987. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77988. return;
  77989. }
  77990. //legacy support for old syntax.
  77991. if (!this._scene && object.getScene) {
  77992. this._scene = object.getScene();
  77993. }
  77994. if (!this._scene) {
  77995. return;
  77996. }
  77997. this._physicsEngine = this._scene.getPhysicsEngine();
  77998. if (!this._physicsEngine) {
  77999. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  78000. }
  78001. else {
  78002. //set the object's quaternion, if not set
  78003. if (!this.object.rotationQuaternion) {
  78004. if (this.object.rotation) {
  78005. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  78006. }
  78007. else {
  78008. this.object.rotationQuaternion = new BABYLON.Quaternion();
  78009. }
  78010. }
  78011. //default options params
  78012. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  78013. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  78014. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  78015. this._joints = [];
  78016. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  78017. if (!this.object.parent || this._options.ignoreParent) {
  78018. this._init();
  78019. }
  78020. else if (this.object.parent.physicsImpostor) {
  78021. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  78022. }
  78023. }
  78024. }
  78025. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  78026. get: function () {
  78027. return this._isDisposed;
  78028. },
  78029. enumerable: true,
  78030. configurable: true
  78031. });
  78032. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  78033. get: function () {
  78034. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  78035. },
  78036. set: function (value) {
  78037. this.setMass(value);
  78038. },
  78039. enumerable: true,
  78040. configurable: true
  78041. });
  78042. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  78043. get: function () {
  78044. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  78045. },
  78046. set: function (value) {
  78047. if (!this._physicsEngine) {
  78048. return;
  78049. }
  78050. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  78051. },
  78052. enumerable: true,
  78053. configurable: true
  78054. });
  78055. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  78056. get: function () {
  78057. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  78058. },
  78059. set: function (value) {
  78060. if (!this._physicsEngine) {
  78061. return;
  78062. }
  78063. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  78064. },
  78065. enumerable: true,
  78066. configurable: true
  78067. });
  78068. /**
  78069. * This function will completly initialize this impostor.
  78070. * It will create a new body - but only if this mesh has no parent.
  78071. * If it has, this impostor will not be used other than to define the impostor
  78072. * of the child mesh.
  78073. */
  78074. PhysicsImpostor.prototype._init = function () {
  78075. if (!this._physicsEngine) {
  78076. return;
  78077. }
  78078. this._physicsEngine.removeImpostor(this);
  78079. this.physicsBody = null;
  78080. this._parent = this._parent || this._getPhysicsParent();
  78081. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  78082. this._physicsEngine.addImpostor(this);
  78083. }
  78084. };
  78085. PhysicsImpostor.prototype._getPhysicsParent = function () {
  78086. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  78087. var parentMesh = this.object.parent;
  78088. return parentMesh.physicsImpostor;
  78089. }
  78090. return null;
  78091. };
  78092. /**
  78093. * Should a new body be generated.
  78094. */
  78095. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  78096. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  78097. };
  78098. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  78099. this.forceUpdate();
  78100. };
  78101. /**
  78102. * Force a regeneration of this or the parent's impostor's body.
  78103. * Use under cautious - This will remove all joints already implemented.
  78104. */
  78105. PhysicsImpostor.prototype.forceUpdate = function () {
  78106. this._init();
  78107. if (this.parent && !this._options.ignoreParent) {
  78108. this.parent.forceUpdate();
  78109. }
  78110. };
  78111. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  78112. /*public get mesh(): AbstractMesh {
  78113. return this._mesh;
  78114. }*/
  78115. /**
  78116. * Gets the body that holds this impostor. Either its own, or its parent.
  78117. */
  78118. get: function () {
  78119. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  78120. },
  78121. /**
  78122. * Set the physics body. Used mainly by the physics engine/plugin
  78123. */
  78124. set: function (physicsBody) {
  78125. if (this._physicsBody && this._physicsEngine) {
  78126. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  78127. }
  78128. this._physicsBody = physicsBody;
  78129. this.resetUpdateFlags();
  78130. },
  78131. enumerable: true,
  78132. configurable: true
  78133. });
  78134. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  78135. get: function () {
  78136. return !this._options.ignoreParent && this._parent ? this._parent : null;
  78137. },
  78138. set: function (value) {
  78139. this._parent = value;
  78140. },
  78141. enumerable: true,
  78142. configurable: true
  78143. });
  78144. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  78145. this._bodyUpdateRequired = false;
  78146. };
  78147. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  78148. if (this.object.getBoundingInfo) {
  78149. var q = this.object.rotationQuaternion;
  78150. //reset rotation
  78151. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  78152. //calculate the world matrix with no rotation
  78153. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  78154. var boundingInfo = this.object.getBoundingInfo();
  78155. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  78156. //bring back the rotation
  78157. this.object.rotationQuaternion = q;
  78158. //calculate the world matrix with the new rotation
  78159. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  78160. return size;
  78161. }
  78162. else {
  78163. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  78164. }
  78165. };
  78166. PhysicsImpostor.prototype.getObjectCenter = function () {
  78167. if (this.object.getBoundingInfo) {
  78168. var boundingInfo = this.object.getBoundingInfo();
  78169. return boundingInfo.boundingBox.centerWorld;
  78170. }
  78171. else {
  78172. return this.object.position;
  78173. }
  78174. };
  78175. /**
  78176. * Get a specific parametes from the options parameter.
  78177. */
  78178. PhysicsImpostor.prototype.getParam = function (paramName) {
  78179. return this._options[paramName];
  78180. };
  78181. /**
  78182. * Sets a specific parameter in the options given to the physics plugin
  78183. */
  78184. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  78185. this._options[paramName] = value;
  78186. this._bodyUpdateRequired = true;
  78187. };
  78188. /**
  78189. * Specifically change the body's mass option. Won't recreate the physics body object
  78190. */
  78191. PhysicsImpostor.prototype.setMass = function (mass) {
  78192. if (this.getParam("mass") !== mass) {
  78193. this.setParam("mass", mass);
  78194. }
  78195. if (this._physicsEngine) {
  78196. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  78197. }
  78198. };
  78199. PhysicsImpostor.prototype.getLinearVelocity = function () {
  78200. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  78201. };
  78202. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  78203. if (this._physicsEngine) {
  78204. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  78205. }
  78206. };
  78207. PhysicsImpostor.prototype.getAngularVelocity = function () {
  78208. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  78209. };
  78210. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  78211. if (this._physicsEngine) {
  78212. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  78213. }
  78214. };
  78215. /**
  78216. * Execute a function with the physics plugin native code.
  78217. * Provide a function the will have two variables - the world object and the physics body object.
  78218. */
  78219. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  78220. if (this._physicsEngine) {
  78221. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  78222. }
  78223. };
  78224. /**
  78225. * Register a function that will be executed before the physics world is stepping forward.
  78226. */
  78227. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  78228. this._onBeforePhysicsStepCallbacks.push(func);
  78229. };
  78230. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  78231. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  78232. if (index > -1) {
  78233. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  78234. }
  78235. else {
  78236. BABYLON.Tools.Warn("Function to remove was not found");
  78237. }
  78238. };
  78239. /**
  78240. * Register a function that will be executed after the physics step
  78241. */
  78242. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  78243. this._onAfterPhysicsStepCallbacks.push(func);
  78244. };
  78245. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  78246. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  78247. if (index > -1) {
  78248. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  78249. }
  78250. else {
  78251. BABYLON.Tools.Warn("Function to remove was not found");
  78252. }
  78253. };
  78254. /**
  78255. * register a function that will be executed when this impostor collides against a different body.
  78256. */
  78257. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  78258. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  78259. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  78260. };
  78261. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  78262. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  78263. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  78264. if (index > -1) {
  78265. this._onPhysicsCollideCallbacks.splice(index, 1);
  78266. }
  78267. else {
  78268. BABYLON.Tools.Warn("Function to remove was not found");
  78269. }
  78270. };
  78271. PhysicsImpostor.prototype.getParentsRotation = function () {
  78272. var parent = this.object.parent;
  78273. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  78274. while (parent) {
  78275. if (parent.rotationQuaternion) {
  78276. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  78277. }
  78278. else {
  78279. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  78280. }
  78281. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  78282. parent = parent.parent;
  78283. }
  78284. return this._tmpQuat;
  78285. };
  78286. /**
  78287. * Apply a force
  78288. */
  78289. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  78290. if (this._physicsEngine) {
  78291. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  78292. }
  78293. return this;
  78294. };
  78295. /**
  78296. * Apply an impulse
  78297. */
  78298. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  78299. if (this._physicsEngine) {
  78300. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  78301. }
  78302. return this;
  78303. };
  78304. /**
  78305. * A help function to create a joint.
  78306. */
  78307. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  78308. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  78309. this.addJoint(otherImpostor, joint);
  78310. return this;
  78311. };
  78312. /**
  78313. * Add a joint to this impostor with a different impostor.
  78314. */
  78315. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  78316. this._joints.push({
  78317. otherImpostor: otherImpostor,
  78318. joint: joint
  78319. });
  78320. if (this._physicsEngine) {
  78321. this._physicsEngine.addJoint(this, otherImpostor, joint);
  78322. }
  78323. return this;
  78324. };
  78325. /**
  78326. * Will keep this body still, in a sleep mode.
  78327. */
  78328. PhysicsImpostor.prototype.sleep = function () {
  78329. if (this._physicsEngine) {
  78330. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  78331. }
  78332. return this;
  78333. };
  78334. /**
  78335. * Wake the body up.
  78336. */
  78337. PhysicsImpostor.prototype.wakeUp = function () {
  78338. if (this._physicsEngine) {
  78339. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  78340. }
  78341. return this;
  78342. };
  78343. PhysicsImpostor.prototype.clone = function (newObject) {
  78344. if (!newObject)
  78345. return null;
  78346. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  78347. };
  78348. PhysicsImpostor.prototype.dispose = function () {
  78349. var _this = this;
  78350. //no dispose if no physics engine is available.
  78351. if (!this._physicsEngine) {
  78352. return;
  78353. }
  78354. this._joints.forEach(function (j) {
  78355. if (_this._physicsEngine) {
  78356. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  78357. }
  78358. });
  78359. //dispose the physics body
  78360. this._physicsEngine.removeImpostor(this);
  78361. if (this.parent) {
  78362. this.parent.forceUpdate();
  78363. }
  78364. else {
  78365. /*this._object.getChildMeshes().forEach(function(mesh) {
  78366. if (mesh.physicsImpostor) {
  78367. if (disposeChildren) {
  78368. mesh.physicsImpostor.dispose();
  78369. mesh.physicsImpostor = null;
  78370. }
  78371. }
  78372. })*/
  78373. }
  78374. this._isDisposed = true;
  78375. };
  78376. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  78377. this._deltaPosition.copyFrom(position);
  78378. };
  78379. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  78380. if (!this._deltaRotation) {
  78381. this._deltaRotation = new BABYLON.Quaternion();
  78382. }
  78383. this._deltaRotation.copyFrom(rotation);
  78384. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  78385. };
  78386. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  78387. if (this._physicsEngine) {
  78388. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  78389. }
  78390. return this;
  78391. };
  78392. PhysicsImpostor.prototype.getRadius = function () {
  78393. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  78394. };
  78395. /**
  78396. * Sync a bone with this impostor
  78397. * @param bone The bone to sync to the impostor.
  78398. * @param boneMesh The mesh that the bone is influencing.
  78399. * @param jointPivot The pivot of the joint / bone in local space.
  78400. * @param distToJoint Optional distance from the impostor to the joint.
  78401. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  78402. */
  78403. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  78404. var tempVec = PhysicsImpostor._tmpVecs[0];
  78405. var mesh = this.object;
  78406. if (mesh.rotationQuaternion) {
  78407. if (adjustRotation) {
  78408. var tempQuat = PhysicsImpostor._tmpQuat;
  78409. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  78410. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  78411. }
  78412. else {
  78413. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  78414. }
  78415. }
  78416. tempVec.x = 0;
  78417. tempVec.y = 0;
  78418. tempVec.z = 0;
  78419. if (jointPivot) {
  78420. tempVec.x = jointPivot.x;
  78421. tempVec.y = jointPivot.y;
  78422. tempVec.z = jointPivot.z;
  78423. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  78424. if (distToJoint === undefined || distToJoint === null) {
  78425. distToJoint = jointPivot.length();
  78426. }
  78427. tempVec.x *= distToJoint;
  78428. tempVec.y *= distToJoint;
  78429. tempVec.z *= distToJoint;
  78430. }
  78431. if (bone.getParent()) {
  78432. tempVec.addInPlace(mesh.getAbsolutePosition());
  78433. bone.setAbsolutePosition(tempVec, boneMesh);
  78434. }
  78435. else {
  78436. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  78437. boneMesh.position.x -= tempVec.x;
  78438. boneMesh.position.y -= tempVec.y;
  78439. boneMesh.position.z -= tempVec.z;
  78440. }
  78441. };
  78442. /**
  78443. * Sync impostor to a bone
  78444. * @param bone The bone that the impostor will be synced to.
  78445. * @param boneMesh The mesh that the bone is influencing.
  78446. * @param jointPivot The pivot of the joint / bone in local space.
  78447. * @param distToJoint Optional distance from the impostor to the joint.
  78448. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  78449. * @param boneAxis Optional vector3 axis the bone is aligned with
  78450. */
  78451. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  78452. var mesh = this.object;
  78453. if (mesh.rotationQuaternion) {
  78454. if (adjustRotation) {
  78455. var tempQuat = PhysicsImpostor._tmpQuat;
  78456. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  78457. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  78458. }
  78459. else {
  78460. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  78461. }
  78462. }
  78463. var pos = PhysicsImpostor._tmpVecs[0];
  78464. var boneDir = PhysicsImpostor._tmpVecs[1];
  78465. if (!boneAxis) {
  78466. boneAxis = PhysicsImpostor._tmpVecs[2];
  78467. boneAxis.x = 0;
  78468. boneAxis.y = 1;
  78469. boneAxis.z = 0;
  78470. }
  78471. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  78472. bone.getAbsolutePositionToRef(boneMesh, pos);
  78473. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  78474. distToJoint = jointPivot.length();
  78475. }
  78476. if (distToJoint !== undefined && distToJoint !== null) {
  78477. pos.x += boneDir.x * distToJoint;
  78478. pos.y += boneDir.y * distToJoint;
  78479. pos.z += boneDir.z * distToJoint;
  78480. }
  78481. mesh.setAbsolutePosition(pos);
  78482. };
  78483. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  78484. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  78485. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78486. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  78487. //Impostor types
  78488. PhysicsImpostor.NoImpostor = 0;
  78489. PhysicsImpostor.SphereImpostor = 1;
  78490. PhysicsImpostor.BoxImpostor = 2;
  78491. PhysicsImpostor.PlaneImpostor = 3;
  78492. PhysicsImpostor.MeshImpostor = 4;
  78493. PhysicsImpostor.CylinderImpostor = 7;
  78494. PhysicsImpostor.ParticleImpostor = 8;
  78495. PhysicsImpostor.HeightmapImpostor = 9;
  78496. return PhysicsImpostor;
  78497. }());
  78498. BABYLON.PhysicsImpostor = PhysicsImpostor;
  78499. })(BABYLON || (BABYLON = {}));
  78500. //# sourceMappingURL=babylon.physicsImpostor.js.map
  78501. "use strict";
  78502. var BABYLON;
  78503. (function (BABYLON) {
  78504. var PhysicsEngine = /** @class */ (function () {
  78505. function PhysicsEngine(gravity, _physicsPlugin) {
  78506. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  78507. this._physicsPlugin = _physicsPlugin;
  78508. //new methods and parameters
  78509. this._impostors = [];
  78510. this._joints = [];
  78511. if (!this._physicsPlugin.isSupported()) {
  78512. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  78513. + "Please make sure it is included.");
  78514. }
  78515. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  78516. this.setGravity(gravity);
  78517. this.setTimeStep();
  78518. }
  78519. PhysicsEngine.prototype.setGravity = function (gravity) {
  78520. this.gravity = gravity;
  78521. this._physicsPlugin.setGravity(this.gravity);
  78522. };
  78523. /**
  78524. * Set the time step of the physics engine.
  78525. * default is 1/60.
  78526. * To slow it down, enter 1/600 for example.
  78527. * To speed it up, 1/30
  78528. * @param {number} newTimeStep the new timestep to apply to this world.
  78529. */
  78530. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  78531. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  78532. this._physicsPlugin.setTimeStep(newTimeStep);
  78533. };
  78534. /**
  78535. * Get the time step of the physics engine.
  78536. */
  78537. PhysicsEngine.prototype.getTimeStep = function () {
  78538. return this._physicsPlugin.getTimeStep();
  78539. };
  78540. PhysicsEngine.prototype.dispose = function () {
  78541. this._impostors.forEach(function (impostor) {
  78542. impostor.dispose();
  78543. });
  78544. this._physicsPlugin.dispose();
  78545. };
  78546. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  78547. return this._physicsPlugin.name;
  78548. };
  78549. /**
  78550. * Adding a new impostor for the impostor tracking.
  78551. * This will be done by the impostor itself.
  78552. * @param {PhysicsImpostor} impostor the impostor to add
  78553. */
  78554. PhysicsEngine.prototype.addImpostor = function (impostor) {
  78555. impostor.uniqueId = this._impostors.push(impostor);
  78556. //if no parent, generate the body
  78557. if (!impostor.parent) {
  78558. this._physicsPlugin.generatePhysicsBody(impostor);
  78559. }
  78560. };
  78561. /**
  78562. * Remove an impostor from the engine.
  78563. * This impostor and its mesh will not longer be updated by the physics engine.
  78564. * @param {PhysicsImpostor} impostor the impostor to remove
  78565. */
  78566. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  78567. var index = this._impostors.indexOf(impostor);
  78568. if (index > -1) {
  78569. var removed = this._impostors.splice(index, 1);
  78570. //Is it needed?
  78571. if (removed.length) {
  78572. //this will also remove it from the world.
  78573. removed[0].physicsBody = null;
  78574. }
  78575. }
  78576. };
  78577. /**
  78578. * Add a joint to the physics engine
  78579. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  78580. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  78581. * @param {PhysicsJoint} the joint that will connect both impostors.
  78582. */
  78583. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  78584. var impostorJoint = {
  78585. mainImpostor: mainImpostor,
  78586. connectedImpostor: connectedImpostor,
  78587. joint: joint
  78588. };
  78589. joint.physicsPlugin = this._physicsPlugin;
  78590. this._joints.push(impostorJoint);
  78591. this._physicsPlugin.generateJoint(impostorJoint);
  78592. };
  78593. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  78594. var matchingJoints = this._joints.filter(function (impostorJoint) {
  78595. return (impostorJoint.connectedImpostor === connectedImpostor
  78596. && impostorJoint.joint === joint
  78597. && impostorJoint.mainImpostor === mainImpostor);
  78598. });
  78599. if (matchingJoints.length) {
  78600. this._physicsPlugin.removeJoint(matchingJoints[0]);
  78601. //TODO remove it from the list as well
  78602. }
  78603. };
  78604. /**
  78605. * Called by the scene. no need to call it.
  78606. */
  78607. PhysicsEngine.prototype._step = function (delta) {
  78608. var _this = this;
  78609. //check if any mesh has no body / requires an update
  78610. this._impostors.forEach(function (impostor) {
  78611. if (impostor.isBodyInitRequired()) {
  78612. _this._physicsPlugin.generatePhysicsBody(impostor);
  78613. }
  78614. });
  78615. if (delta > 0.1) {
  78616. delta = 0.1;
  78617. }
  78618. else if (delta <= 0) {
  78619. delta = 1.0 / 60.0;
  78620. }
  78621. this._physicsPlugin.executeStep(delta, this._impostors);
  78622. };
  78623. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  78624. return this._physicsPlugin;
  78625. };
  78626. PhysicsEngine.prototype.getImpostors = function () {
  78627. return this._impostors;
  78628. };
  78629. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  78630. for (var i = 0; i < this._impostors.length; ++i) {
  78631. if (this._impostors[i].object === object) {
  78632. return this._impostors[i];
  78633. }
  78634. }
  78635. return null;
  78636. };
  78637. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  78638. for (var i = 0; i < this._impostors.length; ++i) {
  78639. if (this._impostors[i].physicsBody === body) {
  78640. return this._impostors[i];
  78641. }
  78642. }
  78643. return null;
  78644. };
  78645. // Statics
  78646. PhysicsEngine.Epsilon = 0.001;
  78647. return PhysicsEngine;
  78648. }());
  78649. BABYLON.PhysicsEngine = PhysicsEngine;
  78650. })(BABYLON || (BABYLON = {}));
  78651. //# sourceMappingURL=babylon.physicsEngine.js.map
  78652. "use strict";
  78653. var BABYLON;
  78654. (function (BABYLON) {
  78655. var PhysicsHelper = /** @class */ (function () {
  78656. function PhysicsHelper(scene) {
  78657. this._scene = scene;
  78658. this._physicsEngine = this._scene.getPhysicsEngine();
  78659. if (!this._physicsEngine) {
  78660. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  78661. }
  78662. }
  78663. /**
  78664. * @param {Vector3} origin the origin of the explosion
  78665. * @param {number} radius the explosion radius
  78666. * @param {number} strength the explosion strength
  78667. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78668. */
  78669. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  78670. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78671. if (!this._physicsEngine) {
  78672. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  78673. return null;
  78674. }
  78675. var impostors = this._physicsEngine.getImpostors();
  78676. if (impostors.length === 0) {
  78677. return null;
  78678. }
  78679. var event = new PhysicsRadialExplosionEvent(this._scene);
  78680. impostors.forEach(function (impostor) {
  78681. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78682. if (!impostorForceAndContactPoint) {
  78683. return;
  78684. }
  78685. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78686. });
  78687. event.dispose(false);
  78688. return event;
  78689. };
  78690. /**
  78691. * @param {Vector3} origin the origin of the explosion
  78692. * @param {number} radius the explosion radius
  78693. * @param {number} strength the explosion strength
  78694. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78695. */
  78696. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  78697. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78698. if (!this._physicsEngine) {
  78699. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78700. return null;
  78701. }
  78702. var impostors = this._physicsEngine.getImpostors();
  78703. if (impostors.length === 0) {
  78704. return null;
  78705. }
  78706. var event = new PhysicsRadialExplosionEvent(this._scene);
  78707. impostors.forEach(function (impostor) {
  78708. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78709. if (!impostorForceAndContactPoint) {
  78710. return;
  78711. }
  78712. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78713. });
  78714. event.dispose(false);
  78715. return event;
  78716. };
  78717. /**
  78718. * @param {Vector3} origin the origin of the explosion
  78719. * @param {number} radius the explosion radius
  78720. * @param {number} strength the explosion strength
  78721. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78722. */
  78723. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  78724. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78725. if (!this._physicsEngine) {
  78726. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78727. return null;
  78728. }
  78729. var impostors = this._physicsEngine.getImpostors();
  78730. if (impostors.length === 0) {
  78731. return null;
  78732. }
  78733. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78734. event.dispose(false);
  78735. return event;
  78736. };
  78737. /**
  78738. * @param {Vector3} origin the origin of the updraft
  78739. * @param {number} radius the radius of the updraft
  78740. * @param {number} strength the strength of the updraft
  78741. * @param {number} height the height of the updraft
  78742. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78743. */
  78744. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78745. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78746. if (!this._physicsEngine) {
  78747. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78748. return null;
  78749. }
  78750. if (this._physicsEngine.getImpostors().length === 0) {
  78751. return null;
  78752. }
  78753. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78754. event.dispose(false);
  78755. return event;
  78756. };
  78757. /**
  78758. * @param {Vector3} origin the of the vortex
  78759. * @param {number} radius the radius of the vortex
  78760. * @param {number} strength the strength of the vortex
  78761. * @param {number} height the height of the vortex
  78762. */
  78763. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78764. if (!this._physicsEngine) {
  78765. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78766. return null;
  78767. }
  78768. if (this._physicsEngine.getImpostors().length === 0) {
  78769. return null;
  78770. }
  78771. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78772. event.dispose(false);
  78773. return event;
  78774. };
  78775. return PhysicsHelper;
  78776. }());
  78777. BABYLON.PhysicsHelper = PhysicsHelper;
  78778. /***** Radial explosion *****/
  78779. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78780. function PhysicsRadialExplosionEvent(scene) {
  78781. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78782. this._rays = [];
  78783. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78784. this._scene = scene;
  78785. }
  78786. /**
  78787. * Returns the data related to the radial explosion event (sphere & rays).
  78788. * @returns {PhysicsRadialExplosionEventData}
  78789. */
  78790. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78791. this._dataFetched = true;
  78792. return {
  78793. sphere: this._sphere,
  78794. rays: this._rays,
  78795. };
  78796. };
  78797. /**
  78798. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78799. * @param impostor
  78800. * @param {Vector3} origin the origin of the explosion
  78801. * @param {number} radius the explosion radius
  78802. * @param {number} strength the explosion strength
  78803. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78804. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78805. */
  78806. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78807. if (impostor.mass === 0) {
  78808. return null;
  78809. }
  78810. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78811. return null;
  78812. }
  78813. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78814. return null;
  78815. }
  78816. var impostorObjectCenter = impostor.getObjectCenter();
  78817. var direction = impostorObjectCenter.subtract(origin);
  78818. var ray = new BABYLON.Ray(origin, direction, radius);
  78819. this._rays.push(ray);
  78820. var hit = ray.intersectsMesh(impostor.object);
  78821. var contactPoint = hit.pickedPoint;
  78822. if (!contactPoint) {
  78823. return null;
  78824. }
  78825. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78826. if (distanceFromOrigin > radius) {
  78827. return null;
  78828. }
  78829. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78830. ? strength
  78831. : strength * (1 - (distanceFromOrigin / radius));
  78832. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78833. return { force: force, contactPoint: contactPoint };
  78834. };
  78835. /**
  78836. * Disposes the sphere.
  78837. * @param {bolean} force
  78838. */
  78839. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78840. var _this = this;
  78841. if (force === void 0) { force = true; }
  78842. if (force) {
  78843. this._sphere.dispose();
  78844. }
  78845. else {
  78846. setTimeout(function () {
  78847. if (!_this._dataFetched) {
  78848. _this._sphere.dispose();
  78849. }
  78850. }, 0);
  78851. }
  78852. };
  78853. /*** Helpers ***/
  78854. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78855. if (!this._sphere) {
  78856. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78857. this._sphere.isVisible = false;
  78858. }
  78859. };
  78860. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78861. var impostorObject = impostor.object;
  78862. this._prepareSphere();
  78863. this._sphere.position = origin;
  78864. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78865. this._sphere._updateBoundingInfo();
  78866. this._sphere.computeWorldMatrix(true);
  78867. return this._sphere.intersectsMesh(impostorObject, true);
  78868. };
  78869. return PhysicsRadialExplosionEvent;
  78870. }());
  78871. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78872. /***** Gravitational Field *****/
  78873. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78874. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78875. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78876. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78877. this._physicsHelper = physicsHelper;
  78878. this._scene = scene;
  78879. this._origin = origin;
  78880. this._radius = radius;
  78881. this._strength = strength;
  78882. this._falloff = falloff;
  78883. this._tickCallback = this._tick.bind(this);
  78884. }
  78885. /**
  78886. * Returns the data related to the gravitational field event (sphere).
  78887. * @returns {PhysicsGravitationalFieldEventData}
  78888. */
  78889. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78890. this._dataFetched = true;
  78891. return {
  78892. sphere: this._sphere,
  78893. };
  78894. };
  78895. /**
  78896. * Enables the gravitational field.
  78897. */
  78898. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78899. this._tickCallback.call(this);
  78900. this._scene.registerBeforeRender(this._tickCallback);
  78901. };
  78902. /**
  78903. * Disables the gravitational field.
  78904. */
  78905. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78906. this._scene.unregisterBeforeRender(this._tickCallback);
  78907. };
  78908. /**
  78909. * Disposes the sphere.
  78910. * @param {bolean} force
  78911. */
  78912. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78913. var _this = this;
  78914. if (force === void 0) { force = true; }
  78915. if (force) {
  78916. this._sphere.dispose();
  78917. }
  78918. else {
  78919. setTimeout(function () {
  78920. if (!_this._dataFetched) {
  78921. _this._sphere.dispose();
  78922. }
  78923. }, 0);
  78924. }
  78925. };
  78926. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78927. // Since the params won't change, we fetch the event only once
  78928. if (this._sphere) {
  78929. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78930. }
  78931. else {
  78932. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78933. if (radialExplosionEvent) {
  78934. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78935. }
  78936. }
  78937. };
  78938. return PhysicsGravitationalFieldEvent;
  78939. }());
  78940. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78941. /***** Updraft *****/
  78942. var PhysicsUpdraftEvent = /** @class */ (function () {
  78943. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78944. this._scene = _scene;
  78945. this._origin = _origin;
  78946. this._radius = _radius;
  78947. this._strength = _strength;
  78948. this._height = _height;
  78949. this._updraftMode = _updraftMode;
  78950. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78951. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78952. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78953. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78954. this._physicsEngine = this._scene.getPhysicsEngine();
  78955. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78956. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78957. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78958. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78959. }
  78960. this._tickCallback = this._tick.bind(this);
  78961. }
  78962. /**
  78963. * Returns the data related to the updraft event (cylinder).
  78964. * @returns {PhysicsUpdraftEventData}
  78965. */
  78966. PhysicsUpdraftEvent.prototype.getData = function () {
  78967. this._dataFetched = true;
  78968. return {
  78969. cylinder: this._cylinder,
  78970. };
  78971. };
  78972. /**
  78973. * Enables the updraft.
  78974. */
  78975. PhysicsUpdraftEvent.prototype.enable = function () {
  78976. this._tickCallback.call(this);
  78977. this._scene.registerBeforeRender(this._tickCallback);
  78978. };
  78979. /**
  78980. * Disables the cortex.
  78981. */
  78982. PhysicsUpdraftEvent.prototype.disable = function () {
  78983. this._scene.unregisterBeforeRender(this._tickCallback);
  78984. };
  78985. /**
  78986. * Disposes the sphere.
  78987. * @param {bolean} force
  78988. */
  78989. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78990. var _this = this;
  78991. if (force === void 0) { force = true; }
  78992. if (force) {
  78993. this._cylinder.dispose();
  78994. }
  78995. else {
  78996. setTimeout(function () {
  78997. if (!_this._dataFetched) {
  78998. _this._cylinder.dispose();
  78999. }
  79000. }, 0);
  79001. }
  79002. };
  79003. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  79004. if (impostor.mass === 0) {
  79005. return null;
  79006. }
  79007. if (!this._intersectsWithCylinder(impostor)) {
  79008. return null;
  79009. }
  79010. var impostorObjectCenter = impostor.getObjectCenter();
  79011. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  79012. var direction = this._originDirection;
  79013. }
  79014. else {
  79015. var direction = impostorObjectCenter.subtract(this._originTop);
  79016. }
  79017. var multiplier = this._strength * -1;
  79018. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  79019. return { force: force, contactPoint: impostorObjectCenter };
  79020. };
  79021. PhysicsUpdraftEvent.prototype._tick = function () {
  79022. var _this = this;
  79023. this._physicsEngine.getImpostors().forEach(function (impostor) {
  79024. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  79025. if (!impostorForceAndContactPoint) {
  79026. return;
  79027. }
  79028. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  79029. });
  79030. };
  79031. /*** Helpers ***/
  79032. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  79033. if (!this._cylinder) {
  79034. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  79035. height: this._height,
  79036. diameter: this._radius * 2,
  79037. }, this._scene);
  79038. this._cylinder.isVisible = false;
  79039. }
  79040. };
  79041. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  79042. var impostorObject = impostor.object;
  79043. this._prepareCylinder();
  79044. this._cylinder.position = this._cylinderPosition;
  79045. return this._cylinder.intersectsMesh(impostorObject, true);
  79046. };
  79047. return PhysicsUpdraftEvent;
  79048. }());
  79049. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  79050. /***** Vortex *****/
  79051. var PhysicsVortexEvent = /** @class */ (function () {
  79052. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  79053. this._scene = _scene;
  79054. this._origin = _origin;
  79055. this._radius = _radius;
  79056. this._strength = _strength;
  79057. this._height = _height;
  79058. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  79059. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  79060. this._updraftMultiplier = 0.02;
  79061. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  79062. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  79063. this._physicsEngine = this._scene.getPhysicsEngine();
  79064. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  79065. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  79066. this._tickCallback = this._tick.bind(this);
  79067. }
  79068. /**
  79069. * Returns the data related to the vortex event (cylinder).
  79070. * @returns {PhysicsVortexEventData}
  79071. */
  79072. PhysicsVortexEvent.prototype.getData = function () {
  79073. this._dataFetched = true;
  79074. return {
  79075. cylinder: this._cylinder,
  79076. };
  79077. };
  79078. /**
  79079. * Enables the vortex.
  79080. */
  79081. PhysicsVortexEvent.prototype.enable = function () {
  79082. this._tickCallback.call(this);
  79083. this._scene.registerBeforeRender(this._tickCallback);
  79084. };
  79085. /**
  79086. * Disables the cortex.
  79087. */
  79088. PhysicsVortexEvent.prototype.disable = function () {
  79089. this._scene.unregisterBeforeRender(this._tickCallback);
  79090. };
  79091. /**
  79092. * Disposes the sphere.
  79093. * @param {bolean} force
  79094. */
  79095. PhysicsVortexEvent.prototype.dispose = function (force) {
  79096. var _this = this;
  79097. if (force === void 0) { force = true; }
  79098. if (force) {
  79099. this._cylinder.dispose();
  79100. }
  79101. else {
  79102. setTimeout(function () {
  79103. if (!_this._dataFetched) {
  79104. _this._cylinder.dispose();
  79105. }
  79106. }, 0);
  79107. }
  79108. };
  79109. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  79110. if (impostor.mass === 0) {
  79111. return null;
  79112. }
  79113. if (!this._intersectsWithCylinder(impostor)) {
  79114. return null;
  79115. }
  79116. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  79117. return null;
  79118. }
  79119. var impostorObjectCenter = impostor.getObjectCenter();
  79120. 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)
  79121. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  79122. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  79123. var hit = ray.intersectsMesh(impostor.object);
  79124. var contactPoint = hit.pickedPoint;
  79125. if (!contactPoint) {
  79126. return null;
  79127. }
  79128. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  79129. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  79130. var directionToOrigin = contactPoint.normalize();
  79131. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  79132. directionToOrigin = directionToOrigin.negate();
  79133. }
  79134. // TODO: find a more physically based solution
  79135. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  79136. var forceX = directionToOrigin.x * this._strength / 8;
  79137. var forceY = directionToOrigin.y * this._updraftMultiplier;
  79138. var forceZ = directionToOrigin.z * this._strength / 8;
  79139. }
  79140. else {
  79141. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  79142. var forceY = this._originTop.y * this._updraftMultiplier;
  79143. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  79144. }
  79145. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  79146. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  79147. return { force: force, contactPoint: impostorObjectCenter };
  79148. };
  79149. PhysicsVortexEvent.prototype._tick = function () {
  79150. var _this = this;
  79151. this._physicsEngine.getImpostors().forEach(function (impostor) {
  79152. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  79153. if (!impostorForceAndContactPoint) {
  79154. return;
  79155. }
  79156. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  79157. });
  79158. };
  79159. /*** Helpers ***/
  79160. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  79161. if (!this._cylinder) {
  79162. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  79163. height: this._height,
  79164. diameter: this._radius * 2,
  79165. }, this._scene);
  79166. this._cylinder.isVisible = false;
  79167. }
  79168. };
  79169. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  79170. var impostorObject = impostor.object;
  79171. this._prepareCylinder();
  79172. this._cylinder.position = this._cylinderPosition;
  79173. return this._cylinder.intersectsMesh(impostorObject, true);
  79174. };
  79175. return PhysicsVortexEvent;
  79176. }());
  79177. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  79178. /***** Enums *****/
  79179. /**
  79180. * The strenght of the force in correspondence to the distance of the affected object
  79181. */
  79182. var PhysicsRadialImpulseFalloff;
  79183. (function (PhysicsRadialImpulseFalloff) {
  79184. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  79185. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  79186. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  79187. /**
  79188. * The strenght of the force in correspondence to the distance of the affected object
  79189. */
  79190. var PhysicsUpdraftMode;
  79191. (function (PhysicsUpdraftMode) {
  79192. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  79193. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  79194. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  79195. })(BABYLON || (BABYLON = {}));
  79196. //# sourceMappingURL=babylon.physicsHelper.js.map
  79197. "use strict";
  79198. var BABYLON;
  79199. (function (BABYLON) {
  79200. var CannonJSPlugin = /** @class */ (function () {
  79201. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  79202. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  79203. if (iterations === void 0) { iterations = 10; }
  79204. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  79205. this.name = "CannonJSPlugin";
  79206. this._physicsMaterials = new Array();
  79207. this._fixedTimeStep = 1 / 60;
  79208. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  79209. this.BJSCANNON = CANNON;
  79210. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  79211. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  79212. this._tmpPosition = BABYLON.Vector3.Zero();
  79213. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  79214. this._tmpUnityRotation = new BABYLON.Quaternion();
  79215. if (!this.isSupported()) {
  79216. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  79217. return;
  79218. }
  79219. this._extendNamespace();
  79220. this.world = new this.BJSCANNON.World();
  79221. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  79222. this.world.solver.iterations = iterations;
  79223. }
  79224. CannonJSPlugin.prototype.setGravity = function (gravity) {
  79225. this.world.gravity.copy(gravity);
  79226. };
  79227. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  79228. this._fixedTimeStep = timeStep;
  79229. };
  79230. CannonJSPlugin.prototype.getTimeStep = function () {
  79231. return this._fixedTimeStep;
  79232. };
  79233. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  79234. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  79235. };
  79236. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79237. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  79238. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  79239. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  79240. };
  79241. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79242. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  79243. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  79244. impostor.physicsBody.applyForce(impulse, worldPoint);
  79245. };
  79246. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79247. //parent-child relationship. Does this impostor has a parent impostor?
  79248. if (impostor.parent) {
  79249. if (impostor.physicsBody) {
  79250. this.removePhysicsBody(impostor);
  79251. //TODO is that needed?
  79252. impostor.forceUpdate();
  79253. }
  79254. return;
  79255. }
  79256. //should a new body be created for this impostor?
  79257. if (impostor.isBodyInitRequired()) {
  79258. var shape = this._createShape(impostor);
  79259. //unregister events, if body is being changed
  79260. var oldBody = impostor.physicsBody;
  79261. if (oldBody) {
  79262. this.removePhysicsBody(impostor);
  79263. }
  79264. //create the body and material
  79265. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  79266. var bodyCreationObject = {
  79267. mass: impostor.getParam("mass"),
  79268. material: material
  79269. };
  79270. // A simple extend, in case native options were used.
  79271. var nativeOptions = impostor.getParam("nativeOptions");
  79272. for (var key in nativeOptions) {
  79273. if (nativeOptions.hasOwnProperty(key)) {
  79274. bodyCreationObject[key] = nativeOptions[key];
  79275. }
  79276. }
  79277. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  79278. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  79279. this.world.addEventListener("preStep", impostor.beforeStep);
  79280. this.world.addEventListener("postStep", impostor.afterStep);
  79281. impostor.physicsBody.addShape(shape);
  79282. this.world.add(impostor.physicsBody);
  79283. //try to keep the body moving in the right direction by taking old properties.
  79284. //Should be tested!
  79285. if (oldBody) {
  79286. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  79287. impostor.physicsBody[param].copy(oldBody[param]);
  79288. });
  79289. }
  79290. this._processChildMeshes(impostor);
  79291. }
  79292. //now update the body's transformation
  79293. this._updatePhysicsBodyTransformation(impostor);
  79294. };
  79295. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  79296. var _this = this;
  79297. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  79298. var currentRotation = mainImpostor.object.rotationQuaternion;
  79299. if (meshChildren.length) {
  79300. var processMesh = function (localPosition, mesh) {
  79301. if (!currentRotation || !mesh.rotationQuaternion) {
  79302. return;
  79303. }
  79304. var childImpostor = mesh.getPhysicsImpostor();
  79305. if (childImpostor) {
  79306. var parent = childImpostor.parent;
  79307. if (parent !== mainImpostor) {
  79308. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  79309. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  79310. if (childImpostor.physicsBody) {
  79311. _this.removePhysicsBody(childImpostor);
  79312. childImpostor.physicsBody = null;
  79313. }
  79314. childImpostor.parent = mainImpostor;
  79315. childImpostor.resetUpdateFlags();
  79316. 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));
  79317. //Add the mass of the children.
  79318. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  79319. }
  79320. }
  79321. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  79322. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  79323. };
  79324. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  79325. }
  79326. };
  79327. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79328. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  79329. this.world.removeEventListener("preStep", impostor.beforeStep);
  79330. this.world.removeEventListener("postStep", impostor.afterStep);
  79331. this.world.remove(impostor.physicsBody);
  79332. };
  79333. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79334. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79335. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79336. if (!mainBody || !connectedBody) {
  79337. return;
  79338. }
  79339. var constraint;
  79340. var jointData = impostorJoint.joint.jointData;
  79341. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  79342. var constraintData = {
  79343. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  79344. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  79345. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  79346. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  79347. maxForce: jointData.nativeParams.maxForce,
  79348. collideConnected: !!jointData.collision
  79349. };
  79350. switch (impostorJoint.joint.type) {
  79351. case BABYLON.PhysicsJoint.HingeJoint:
  79352. case BABYLON.PhysicsJoint.Hinge2Joint:
  79353. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  79354. break;
  79355. case BABYLON.PhysicsJoint.DistanceJoint:
  79356. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  79357. break;
  79358. case BABYLON.PhysicsJoint.SpringJoint:
  79359. var springData = jointData;
  79360. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  79361. restLength: springData.length,
  79362. stiffness: springData.stiffness,
  79363. damping: springData.damping,
  79364. localAnchorA: constraintData.pivotA,
  79365. localAnchorB: constraintData.pivotB
  79366. });
  79367. break;
  79368. case BABYLON.PhysicsJoint.LockJoint:
  79369. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  79370. break;
  79371. case BABYLON.PhysicsJoint.PointToPointJoint:
  79372. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79373. default:
  79374. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  79375. break;
  79376. }
  79377. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  79378. constraint.collideConnected = !!jointData.collision;
  79379. impostorJoint.joint.physicsJoint = constraint;
  79380. //don't add spring as constraint, as it is not one.
  79381. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  79382. this.world.addConstraint(constraint);
  79383. }
  79384. else {
  79385. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  79386. constraint.applyForce();
  79387. });
  79388. }
  79389. };
  79390. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79391. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  79392. };
  79393. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  79394. var index;
  79395. var mat;
  79396. for (index = 0; index < this._physicsMaterials.length; index++) {
  79397. mat = this._physicsMaterials[index];
  79398. if (mat.friction === friction && mat.restitution === restitution) {
  79399. return mat;
  79400. }
  79401. }
  79402. var currentMat = new this.BJSCANNON.Material(name);
  79403. currentMat.friction = friction;
  79404. currentMat.restitution = restitution;
  79405. this._physicsMaterials.push(currentMat);
  79406. return currentMat;
  79407. };
  79408. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  79409. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  79410. };
  79411. CannonJSPlugin.prototype._createShape = function (impostor) {
  79412. var object = impostor.object;
  79413. var returnValue;
  79414. var extendSize = impostor.getObjectExtendSize();
  79415. switch (impostor.type) {
  79416. case BABYLON.PhysicsImpostor.SphereImpostor:
  79417. var radiusX = extendSize.x;
  79418. var radiusY = extendSize.y;
  79419. var radiusZ = extendSize.z;
  79420. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  79421. break;
  79422. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  79423. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79424. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  79425. break;
  79426. case BABYLON.PhysicsImpostor.BoxImpostor:
  79427. var box = extendSize.scale(0.5);
  79428. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  79429. break;
  79430. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79431. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  79432. returnValue = new this.BJSCANNON.Plane();
  79433. break;
  79434. case BABYLON.PhysicsImpostor.MeshImpostor:
  79435. // should transform the vertex data to world coordinates!!
  79436. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  79437. var rawFaces = object.getIndices ? object.getIndices() : [];
  79438. if (!rawVerts)
  79439. return;
  79440. // get only scale! so the object could transform correctly.
  79441. var oldPosition = object.position.clone();
  79442. var oldRotation = object.rotation && object.rotation.clone();
  79443. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  79444. object.position.copyFromFloats(0, 0, 0);
  79445. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  79446. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  79447. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  79448. var transform = object.computeWorldMatrix(true);
  79449. // convert rawVerts to object space
  79450. var temp = new Array();
  79451. var index;
  79452. for (index = 0; index < rawVerts.length; index += 3) {
  79453. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  79454. }
  79455. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  79456. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  79457. //now set back the transformation!
  79458. object.position.copyFrom(oldPosition);
  79459. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  79460. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  79461. break;
  79462. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  79463. var oldPosition2 = object.position.clone();
  79464. var oldRotation2 = object.rotation && object.rotation.clone();
  79465. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  79466. object.position.copyFromFloats(0, 0, 0);
  79467. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  79468. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  79469. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  79470. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  79471. returnValue = this._createHeightmap(object);
  79472. object.position.copyFrom(oldPosition2);
  79473. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  79474. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  79475. object.computeWorldMatrix(true);
  79476. break;
  79477. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79478. returnValue = new this.BJSCANNON.Particle();
  79479. break;
  79480. }
  79481. return returnValue;
  79482. };
  79483. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  79484. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79485. var transform = object.computeWorldMatrix(true);
  79486. // convert rawVerts to object space
  79487. var temp = new Array();
  79488. var index;
  79489. for (index = 0; index < pos.length; index += 3) {
  79490. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  79491. }
  79492. pos = temp;
  79493. var matrix = new Array();
  79494. //For now pointDepth will not be used and will be automatically calculated.
  79495. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  79496. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  79497. var boundingInfo = object.getBoundingInfo();
  79498. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  79499. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  79500. var elementSize = dim * 2 / arraySize;
  79501. for (var i = 0; i < pos.length; i = i + 3) {
  79502. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  79503. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  79504. var y = -pos[i + 2] + minY;
  79505. if (!matrix[x]) {
  79506. matrix[x] = [];
  79507. }
  79508. if (!matrix[x][z]) {
  79509. matrix[x][z] = y;
  79510. }
  79511. matrix[x][z] = Math.max(y, matrix[x][z]);
  79512. }
  79513. for (var x = 0; x <= arraySize; ++x) {
  79514. if (!matrix[x]) {
  79515. var loc = 1;
  79516. while (!matrix[(x + loc) % arraySize]) {
  79517. loc++;
  79518. }
  79519. matrix[x] = matrix[(x + loc) % arraySize].slice();
  79520. //console.log("missing x", x);
  79521. }
  79522. for (var z = 0; z <= arraySize; ++z) {
  79523. if (!matrix[x][z]) {
  79524. var loc = 1;
  79525. var newValue;
  79526. while (newValue === undefined) {
  79527. newValue = matrix[x][(z + loc++) % arraySize];
  79528. }
  79529. matrix[x][z] = newValue;
  79530. }
  79531. }
  79532. }
  79533. var shape = new this.BJSCANNON.Heightfield(matrix, {
  79534. elementSize: elementSize
  79535. });
  79536. //For future reference, needed for body transformation
  79537. shape.minY = minY;
  79538. return shape;
  79539. };
  79540. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  79541. var object = impostor.object;
  79542. //make sure it is updated...
  79543. object.computeWorldMatrix && object.computeWorldMatrix(true);
  79544. // The delta between the mesh position and the mesh bounding box center
  79545. var bInfo = object.getBoundingInfo();
  79546. if (!bInfo)
  79547. return;
  79548. var center = impostor.getObjectCenter();
  79549. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  79550. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  79551. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  79552. this._tmpPosition.copyFrom(center);
  79553. var quaternion = object.rotationQuaternion;
  79554. if (!quaternion) {
  79555. return;
  79556. }
  79557. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  79558. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  79559. //-90 DEG in X, precalculated
  79560. quaternion = quaternion.multiply(this._minus90X);
  79561. //Invert! (Precalculated, 90 deg in X)
  79562. //No need to clone. this will never change.
  79563. impostor.setDeltaRotation(this._plus90X);
  79564. }
  79565. //If it is a heightfield, if should be centered.
  79566. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  79567. var mesh = object;
  79568. var boundingInfo = mesh.getBoundingInfo();
  79569. //calculate the correct body position:
  79570. var rotationQuaternion = mesh.rotationQuaternion;
  79571. mesh.rotationQuaternion = this._tmpUnityRotation;
  79572. mesh.computeWorldMatrix(true);
  79573. //get original center with no rotation
  79574. var c = center.clone();
  79575. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  79576. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  79577. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  79578. mesh.setPreTransformMatrix(p);
  79579. mesh.computeWorldMatrix(true);
  79580. //calculate the translation
  79581. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  79582. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  79583. //add it inverted to the delta
  79584. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  79585. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  79586. //rotation is back
  79587. mesh.rotationQuaternion = rotationQuaternion;
  79588. mesh.setPreTransformMatrix(oldPivot);
  79589. mesh.computeWorldMatrix(true);
  79590. }
  79591. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  79592. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  79593. //this._tmpPosition.copyFrom(object.position);
  79594. }
  79595. impostor.setDeltaPosition(this._tmpDeltaPosition);
  79596. //Now update the impostor object
  79597. impostor.physicsBody.position.copy(this._tmpPosition);
  79598. impostor.physicsBody.quaternion.copy(quaternion);
  79599. };
  79600. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79601. impostor.object.position.copyFrom(impostor.physicsBody.position);
  79602. if (impostor.object.rotationQuaternion) {
  79603. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  79604. }
  79605. };
  79606. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79607. impostor.physicsBody.position.copy(newPosition);
  79608. impostor.physicsBody.quaternion.copy(newRotation);
  79609. };
  79610. CannonJSPlugin.prototype.isSupported = function () {
  79611. return this.BJSCANNON !== undefined;
  79612. };
  79613. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79614. impostor.physicsBody.velocity.copy(velocity);
  79615. };
  79616. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79617. impostor.physicsBody.angularVelocity.copy(velocity);
  79618. };
  79619. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79620. var v = impostor.physicsBody.velocity;
  79621. if (!v) {
  79622. return null;
  79623. }
  79624. return new BABYLON.Vector3(v.x, v.y, v.z);
  79625. };
  79626. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79627. var v = impostor.physicsBody.angularVelocity;
  79628. if (!v) {
  79629. return null;
  79630. }
  79631. return new BABYLON.Vector3(v.x, v.y, v.z);
  79632. };
  79633. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79634. impostor.physicsBody.mass = mass;
  79635. impostor.physicsBody.updateMassProperties();
  79636. };
  79637. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  79638. return impostor.physicsBody.mass;
  79639. };
  79640. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  79641. return impostor.physicsBody.material.friction;
  79642. };
  79643. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79644. impostor.physicsBody.material.friction = friction;
  79645. };
  79646. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79647. return impostor.physicsBody.material.restitution;
  79648. };
  79649. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79650. impostor.physicsBody.material.restitution = restitution;
  79651. };
  79652. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  79653. impostor.physicsBody.sleep();
  79654. };
  79655. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  79656. impostor.physicsBody.wakeUp();
  79657. };
  79658. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79659. joint.physicsJoint.distance = maxDistance;
  79660. };
  79661. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79662. // if (!motorIndex) {
  79663. // joint.physicsJoint.enableMotor();
  79664. // }
  79665. // }
  79666. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79667. // if (!motorIndex) {
  79668. // joint.physicsJoint.disableMotor();
  79669. // }
  79670. // }
  79671. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79672. if (!motorIndex) {
  79673. joint.physicsJoint.enableMotor();
  79674. joint.physicsJoint.setMotorSpeed(speed);
  79675. if (maxForce) {
  79676. this.setLimit(joint, maxForce);
  79677. }
  79678. }
  79679. };
  79680. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  79681. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  79682. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  79683. };
  79684. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79685. var body = impostor.physicsBody;
  79686. mesh.position.x = body.position.x;
  79687. mesh.position.y = body.position.y;
  79688. mesh.position.z = body.position.z;
  79689. if (mesh.rotationQuaternion) {
  79690. mesh.rotationQuaternion.x = body.quaternion.x;
  79691. mesh.rotationQuaternion.y = body.quaternion.y;
  79692. mesh.rotationQuaternion.z = body.quaternion.z;
  79693. mesh.rotationQuaternion.w = body.quaternion.w;
  79694. }
  79695. };
  79696. CannonJSPlugin.prototype.getRadius = function (impostor) {
  79697. var shape = impostor.physicsBody.shapes[0];
  79698. return shape.boundingSphereRadius;
  79699. };
  79700. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79701. var shape = impostor.physicsBody.shapes[0];
  79702. result.x = shape.halfExtents.x * 2;
  79703. result.y = shape.halfExtents.y * 2;
  79704. result.z = shape.halfExtents.z * 2;
  79705. };
  79706. CannonJSPlugin.prototype.dispose = function () {
  79707. };
  79708. CannonJSPlugin.prototype._extendNamespace = function () {
  79709. //this will force cannon to execute at least one step when using interpolation
  79710. var step_tmp1 = new this.BJSCANNON.Vec3();
  79711. var Engine = this.BJSCANNON;
  79712. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  79713. maxSubSteps = maxSubSteps || 10;
  79714. timeSinceLastCalled = timeSinceLastCalled || 0;
  79715. if (timeSinceLastCalled === 0) {
  79716. this.internalStep(dt);
  79717. this.time += dt;
  79718. }
  79719. else {
  79720. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  79721. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  79722. var t0 = performance.now();
  79723. for (var i = 0; i !== internalSteps; i++) {
  79724. this.internalStep(dt);
  79725. if (performance.now() - t0 > dt * 1000) {
  79726. break;
  79727. }
  79728. }
  79729. this.time += timeSinceLastCalled;
  79730. var h = this.time % dt;
  79731. var h_div_dt = h / dt;
  79732. var interpvelo = step_tmp1;
  79733. var bodies = this.bodies;
  79734. for (var j = 0; j !== bodies.length; j++) {
  79735. var b = bodies[j];
  79736. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79737. b.position.vsub(b.previousPosition, interpvelo);
  79738. interpvelo.scale(h_div_dt, interpvelo);
  79739. b.position.vadd(interpvelo, b.interpolatedPosition);
  79740. }
  79741. else {
  79742. b.interpolatedPosition.copy(b.position);
  79743. b.interpolatedQuaternion.copy(b.quaternion);
  79744. }
  79745. }
  79746. }
  79747. };
  79748. };
  79749. return CannonJSPlugin;
  79750. }());
  79751. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79752. })(BABYLON || (BABYLON = {}));
  79753. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79754. "use strict";
  79755. var BABYLON;
  79756. (function (BABYLON) {
  79757. var OimoJSPlugin = /** @class */ (function () {
  79758. function OimoJSPlugin(iterations) {
  79759. this.name = "OimoJSPlugin";
  79760. this._tmpImpostorsArray = [];
  79761. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79762. this.BJSOIMO = OIMO;
  79763. this.world = new this.BJSOIMO.World({
  79764. iterations: iterations
  79765. });
  79766. this.world.clear();
  79767. }
  79768. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79769. this.world.gravity.copy(gravity);
  79770. };
  79771. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79772. this.world.timeStep = timeStep;
  79773. };
  79774. OimoJSPlugin.prototype.getTimeStep = function () {
  79775. return this.world.timeStep;
  79776. };
  79777. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79778. var _this = this;
  79779. impostors.forEach(function (impostor) {
  79780. impostor.beforeStep();
  79781. });
  79782. this.world.step();
  79783. impostors.forEach(function (impostor) {
  79784. impostor.afterStep();
  79785. //update the ordered impostors array
  79786. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79787. });
  79788. //check for collisions
  79789. var contact = this.world.contacts;
  79790. while (contact !== null) {
  79791. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79792. contact = contact.next;
  79793. continue;
  79794. }
  79795. //is this body colliding with any other? get the impostor
  79796. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79797. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79798. if (!mainImpostor || !collidingImpostor) {
  79799. contact = contact.next;
  79800. continue;
  79801. }
  79802. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79803. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79804. contact = contact.next;
  79805. }
  79806. };
  79807. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79808. var mass = impostor.physicsBody.mass;
  79809. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79810. };
  79811. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79812. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79813. this.applyImpulse(impostor, force, contactPoint);
  79814. };
  79815. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79816. var _this = this;
  79817. //parent-child relationship. Does this impostor has a parent impostor?
  79818. if (impostor.parent) {
  79819. if (impostor.physicsBody) {
  79820. this.removePhysicsBody(impostor);
  79821. //TODO is that needed?
  79822. impostor.forceUpdate();
  79823. }
  79824. return;
  79825. }
  79826. if (impostor.isBodyInitRequired()) {
  79827. var bodyConfig = {
  79828. name: impostor.uniqueId,
  79829. //Oimo must have mass, also for static objects.
  79830. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79831. size: [],
  79832. type: [],
  79833. pos: [],
  79834. posShape: [],
  79835. rot: [],
  79836. rotShape: [],
  79837. move: impostor.getParam("mass") !== 0,
  79838. density: impostor.getParam("mass"),
  79839. friction: impostor.getParam("friction"),
  79840. restitution: impostor.getParam("restitution"),
  79841. //Supporting older versions of Oimo
  79842. world: this.world
  79843. };
  79844. var impostors = [impostor];
  79845. var addToArray = function (parent) {
  79846. if (!parent.getChildMeshes)
  79847. return;
  79848. parent.getChildMeshes().forEach(function (m) {
  79849. if (m.physicsImpostor) {
  79850. impostors.push(m.physicsImpostor);
  79851. //m.physicsImpostor._init();
  79852. }
  79853. });
  79854. };
  79855. addToArray(impostor.object);
  79856. var checkWithEpsilon_1 = function (value) {
  79857. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79858. };
  79859. impostors.forEach(function (i) {
  79860. if (!i.object.rotationQuaternion) {
  79861. return;
  79862. }
  79863. //get the correct bounding box
  79864. var oldQuaternion = i.object.rotationQuaternion;
  79865. var rot = oldQuaternion.toEulerAngles();
  79866. var extendSize = i.getObjectExtendSize();
  79867. var radToDeg = 57.295779513082320876;
  79868. if (i === impostor) {
  79869. var center = impostor.getObjectCenter();
  79870. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79871. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79872. //Can also use Array.prototype.push.apply
  79873. bodyConfig.pos.push(center.x);
  79874. bodyConfig.pos.push(center.y);
  79875. bodyConfig.pos.push(center.z);
  79876. bodyConfig.posShape.push(0, 0, 0);
  79877. //tmp solution
  79878. bodyConfig.rot.push(rot.x * radToDeg);
  79879. bodyConfig.rot.push(rot.y * radToDeg);
  79880. bodyConfig.rot.push(rot.z * radToDeg);
  79881. bodyConfig.rotShape.push(0, 0, 0);
  79882. }
  79883. else {
  79884. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79885. bodyConfig.posShape.push(localPosition.x);
  79886. bodyConfig.posShape.push(localPosition.y);
  79887. bodyConfig.posShape.push(localPosition.z);
  79888. bodyConfig.pos.push(0, 0, 0);
  79889. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79890. bodyConfig.rot.push(0);
  79891. bodyConfig.rot.push(0);
  79892. bodyConfig.rot.push(0);
  79893. bodyConfig.rotShape.push(rot.x * radToDeg);
  79894. bodyConfig.rotShape.push(rot.y * radToDeg);
  79895. bodyConfig.rotShape.push(rot.z * radToDeg);
  79896. }
  79897. // register mesh
  79898. switch (i.type) {
  79899. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79900. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79901. case BABYLON.PhysicsImpostor.SphereImpostor:
  79902. var radiusX = extendSize.x;
  79903. var radiusY = extendSize.y;
  79904. var radiusZ = extendSize.z;
  79905. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79906. bodyConfig.type.push('sphere');
  79907. //due to the way oimo works with compounds, add 3 times
  79908. bodyConfig.size.push(size);
  79909. bodyConfig.size.push(size);
  79910. bodyConfig.size.push(size);
  79911. break;
  79912. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79913. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79914. var sizeY = checkWithEpsilon_1(extendSize.y);
  79915. bodyConfig.type.push('cylinder');
  79916. bodyConfig.size.push(sizeX);
  79917. bodyConfig.size.push(sizeY);
  79918. //due to the way oimo works with compounds, add one more value.
  79919. bodyConfig.size.push(sizeY);
  79920. break;
  79921. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79922. case BABYLON.PhysicsImpostor.BoxImpostor:
  79923. default:
  79924. var sizeX = checkWithEpsilon_1(extendSize.x);
  79925. var sizeY = checkWithEpsilon_1(extendSize.y);
  79926. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79927. bodyConfig.type.push('box');
  79928. //if (i === impostor) {
  79929. bodyConfig.size.push(sizeX);
  79930. bodyConfig.size.push(sizeY);
  79931. bodyConfig.size.push(sizeZ);
  79932. //} else {
  79933. // bodyConfig.size.push(0,0,0);
  79934. //}
  79935. break;
  79936. }
  79937. //actually not needed, but hey...
  79938. i.object.rotationQuaternion = oldQuaternion;
  79939. });
  79940. impostor.physicsBody = this.world.add(bodyConfig);
  79941. }
  79942. else {
  79943. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79944. }
  79945. impostor.setDeltaPosition(this._tmpPositionVector);
  79946. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79947. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79948. };
  79949. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79950. //impostor.physicsBody.dispose();
  79951. //Same as : (older oimo versions)
  79952. this.world.removeRigidBody(impostor.physicsBody);
  79953. };
  79954. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79955. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79956. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79957. if (!mainBody || !connectedBody) {
  79958. return;
  79959. }
  79960. var jointData = impostorJoint.joint.jointData;
  79961. var options = jointData.nativeParams || {};
  79962. var type;
  79963. var nativeJointData = {
  79964. body1: mainBody,
  79965. body2: connectedBody,
  79966. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79967. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79968. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79969. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79970. min: options.min,
  79971. max: options.max,
  79972. collision: options.collision || jointData.collision,
  79973. spring: options.spring,
  79974. //supporting older version of Oimo
  79975. world: this.world
  79976. };
  79977. switch (impostorJoint.joint.type) {
  79978. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79979. type = "jointBall";
  79980. break;
  79981. case BABYLON.PhysicsJoint.SpringJoint:
  79982. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79983. var springData = jointData;
  79984. nativeJointData.min = springData.length || nativeJointData.min;
  79985. //Max should also be set, just make sure it is at least min
  79986. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79987. case BABYLON.PhysicsJoint.DistanceJoint:
  79988. type = "jointDistance";
  79989. nativeJointData.max = jointData.maxDistance;
  79990. break;
  79991. case BABYLON.PhysicsJoint.PrismaticJoint:
  79992. type = "jointPrisme";
  79993. break;
  79994. case BABYLON.PhysicsJoint.SliderJoint:
  79995. type = "jointSlide";
  79996. break;
  79997. case BABYLON.PhysicsJoint.WheelJoint:
  79998. type = "jointWheel";
  79999. break;
  80000. case BABYLON.PhysicsJoint.HingeJoint:
  80001. default:
  80002. type = "jointHinge";
  80003. break;
  80004. }
  80005. nativeJointData.type = type;
  80006. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  80007. };
  80008. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  80009. //Bug in Oimo prevents us from disposing a joint in the playground
  80010. //joint.joint.physicsJoint.dispose();
  80011. //So we will bruteforce it!
  80012. try {
  80013. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  80014. }
  80015. catch (e) {
  80016. BABYLON.Tools.Warn(e);
  80017. }
  80018. };
  80019. OimoJSPlugin.prototype.isSupported = function () {
  80020. return this.BJSOIMO !== undefined;
  80021. };
  80022. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  80023. if (!impostor.physicsBody.sleeping) {
  80024. //TODO check that
  80025. /*if (impostor.physicsBody.shapes.next) {
  80026. var parentShape = this._getLastShape(impostor.physicsBody);
  80027. impostor.object.position.copyFrom(parentShape.position);
  80028. console.log(parentShape.position);
  80029. } else {*/
  80030. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  80031. //}
  80032. if (impostor.object.rotationQuaternion) {
  80033. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  80034. }
  80035. }
  80036. };
  80037. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  80038. var body = impostor.physicsBody;
  80039. body.position.copy(newPosition);
  80040. body.orientation.copy(newRotation);
  80041. body.syncShapes();
  80042. body.awake();
  80043. };
  80044. /*private _getLastShape(body: any): any {
  80045. var lastShape = body.shapes;
  80046. while (lastShape.next) {
  80047. lastShape = lastShape.next;
  80048. }
  80049. return lastShape;
  80050. }*/
  80051. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  80052. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  80053. };
  80054. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  80055. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  80056. };
  80057. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  80058. var v = impostor.physicsBody.linearVelocity;
  80059. if (!v) {
  80060. return null;
  80061. }
  80062. return new BABYLON.Vector3(v.x, v.y, v.z);
  80063. };
  80064. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  80065. var v = impostor.physicsBody.angularVelocity;
  80066. if (!v) {
  80067. return null;
  80068. }
  80069. return new BABYLON.Vector3(v.x, v.y, v.z);
  80070. };
  80071. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  80072. var staticBody = mass === 0;
  80073. //this will actually set the body's density and not its mass.
  80074. //But this is how oimo treats the mass variable.
  80075. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  80076. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  80077. };
  80078. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  80079. return impostor.physicsBody.shapes.density;
  80080. };
  80081. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  80082. return impostor.physicsBody.shapes.friction;
  80083. };
  80084. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  80085. impostor.physicsBody.shapes.friction = friction;
  80086. };
  80087. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  80088. return impostor.physicsBody.shapes.restitution;
  80089. };
  80090. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  80091. impostor.physicsBody.shapes.restitution = restitution;
  80092. };
  80093. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  80094. impostor.physicsBody.sleep();
  80095. };
  80096. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  80097. impostor.physicsBody.awake();
  80098. };
  80099. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  80100. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  80101. if (minDistance !== void 0) {
  80102. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  80103. }
  80104. };
  80105. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  80106. //TODO separate rotational and transational motors.
  80107. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  80108. if (motor) {
  80109. motor.setMotor(speed, maxForce);
  80110. }
  80111. };
  80112. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  80113. //TODO separate rotational and transational motors.
  80114. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  80115. if (motor) {
  80116. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  80117. }
  80118. };
  80119. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  80120. var body = impostor.physicsBody;
  80121. mesh.position.x = body.position.x;
  80122. mesh.position.y = body.position.y;
  80123. mesh.position.z = body.position.z;
  80124. if (mesh.rotationQuaternion) {
  80125. mesh.rotationQuaternion.x = body.orientation.x;
  80126. mesh.rotationQuaternion.y = body.orientation.y;
  80127. mesh.rotationQuaternion.z = body.orientation.z;
  80128. mesh.rotationQuaternion.w = body.orientation.s;
  80129. }
  80130. };
  80131. OimoJSPlugin.prototype.getRadius = function (impostor) {
  80132. return impostor.physicsBody.shapes.radius;
  80133. };
  80134. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  80135. var shape = impostor.physicsBody.shapes;
  80136. result.x = shape.halfWidth * 2;
  80137. result.y = shape.halfHeight * 2;
  80138. result.z = shape.halfDepth * 2;
  80139. };
  80140. OimoJSPlugin.prototype.dispose = function () {
  80141. this.world.clear();
  80142. };
  80143. return OimoJSPlugin;
  80144. }());
  80145. BABYLON.OimoJSPlugin = OimoJSPlugin;
  80146. })(BABYLON || (BABYLON = {}));
  80147. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  80148. "use strict";
  80149. var BABYLON;
  80150. (function (BABYLON) {
  80151. /*
  80152. * Based on jsTGALoader - Javascript loader for TGA file
  80153. * By Vincent Thibault
  80154. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  80155. */
  80156. var TGATools = /** @class */ (function () {
  80157. function TGATools() {
  80158. }
  80159. TGATools.GetTGAHeader = function (data) {
  80160. var offset = 0;
  80161. var header = {
  80162. id_length: data[offset++],
  80163. colormap_type: data[offset++],
  80164. image_type: data[offset++],
  80165. colormap_index: data[offset++] | data[offset++] << 8,
  80166. colormap_length: data[offset++] | data[offset++] << 8,
  80167. colormap_size: data[offset++],
  80168. origin: [
  80169. data[offset++] | data[offset++] << 8,
  80170. data[offset++] | data[offset++] << 8
  80171. ],
  80172. width: data[offset++] | data[offset++] << 8,
  80173. height: data[offset++] | data[offset++] << 8,
  80174. pixel_size: data[offset++],
  80175. flags: data[offset++]
  80176. };
  80177. return header;
  80178. };
  80179. TGATools.UploadContent = function (gl, data) {
  80180. // Not enough data to contain header ?
  80181. if (data.length < 19) {
  80182. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  80183. return;
  80184. }
  80185. // Read Header
  80186. var offset = 18;
  80187. var header = TGATools.GetTGAHeader(data);
  80188. // Assume it's a valid Targa file.
  80189. if (header.id_length + offset > data.length) {
  80190. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  80191. return;
  80192. }
  80193. // Skip not needed data
  80194. offset += header.id_length;
  80195. var use_rle = false;
  80196. var use_pal = false;
  80197. var use_grey = false;
  80198. // Get some informations.
  80199. switch (header.image_type) {
  80200. case TGATools._TYPE_RLE_INDEXED:
  80201. use_rle = true;
  80202. case TGATools._TYPE_INDEXED:
  80203. use_pal = true;
  80204. break;
  80205. case TGATools._TYPE_RLE_RGB:
  80206. use_rle = true;
  80207. case TGATools._TYPE_RGB:
  80208. // use_rgb = true;
  80209. break;
  80210. case TGATools._TYPE_RLE_GREY:
  80211. use_rle = true;
  80212. case TGATools._TYPE_GREY:
  80213. use_grey = true;
  80214. break;
  80215. }
  80216. var pixel_data;
  80217. // var numAlphaBits = header.flags & 0xf;
  80218. var pixel_size = header.pixel_size >> 3;
  80219. var pixel_total = header.width * header.height * pixel_size;
  80220. // Read palettes
  80221. var palettes;
  80222. if (use_pal) {
  80223. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  80224. }
  80225. // Read LRE
  80226. if (use_rle) {
  80227. pixel_data = new Uint8Array(pixel_total);
  80228. var c, count, i;
  80229. var localOffset = 0;
  80230. var pixels = new Uint8Array(pixel_size);
  80231. while (offset < pixel_total && localOffset < pixel_total) {
  80232. c = data[offset++];
  80233. count = (c & 0x7f) + 1;
  80234. // RLE pixels
  80235. if (c & 0x80) {
  80236. // Bind pixel tmp array
  80237. for (i = 0; i < pixel_size; ++i) {
  80238. pixels[i] = data[offset++];
  80239. }
  80240. // Copy pixel array
  80241. for (i = 0; i < count; ++i) {
  80242. pixel_data.set(pixels, localOffset + i * pixel_size);
  80243. }
  80244. localOffset += pixel_size * count;
  80245. }
  80246. else {
  80247. count *= pixel_size;
  80248. for (i = 0; i < count; ++i) {
  80249. pixel_data[localOffset + i] = data[offset++];
  80250. }
  80251. localOffset += count;
  80252. }
  80253. }
  80254. }
  80255. else {
  80256. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  80257. }
  80258. // Load to texture
  80259. var x_start, y_start, x_step, y_step, y_end, x_end;
  80260. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  80261. default:
  80262. case TGATools._ORIGIN_UL:
  80263. x_start = 0;
  80264. x_step = 1;
  80265. x_end = header.width;
  80266. y_start = 0;
  80267. y_step = 1;
  80268. y_end = header.height;
  80269. break;
  80270. case TGATools._ORIGIN_BL:
  80271. x_start = 0;
  80272. x_step = 1;
  80273. x_end = header.width;
  80274. y_start = header.height - 1;
  80275. y_step = -1;
  80276. y_end = -1;
  80277. break;
  80278. case TGATools._ORIGIN_UR:
  80279. x_start = header.width - 1;
  80280. x_step = -1;
  80281. x_end = -1;
  80282. y_start = 0;
  80283. y_step = 1;
  80284. y_end = header.height;
  80285. break;
  80286. case TGATools._ORIGIN_BR:
  80287. x_start = header.width - 1;
  80288. x_step = -1;
  80289. x_end = -1;
  80290. y_start = header.height - 1;
  80291. y_step = -1;
  80292. y_end = -1;
  80293. break;
  80294. }
  80295. // Load the specify method
  80296. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  80297. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  80298. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  80299. };
  80300. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80301. var image = pixel_data, colormap = palettes;
  80302. var width = header.width, height = header.height;
  80303. var color, i = 0, x, y;
  80304. var imageData = new Uint8Array(width * height * 4);
  80305. for (y = y_start; y !== y_end; y += y_step) {
  80306. for (x = x_start; x !== x_end; x += x_step, i++) {
  80307. color = image[i];
  80308. imageData[(x + width * y) * 4 + 3] = 255;
  80309. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  80310. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  80311. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  80312. }
  80313. }
  80314. return imageData;
  80315. };
  80316. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80317. var image = pixel_data;
  80318. var width = header.width, height = header.height;
  80319. var color, i = 0, x, y;
  80320. var imageData = new Uint8Array(width * height * 4);
  80321. for (y = y_start; y !== y_end; y += y_step) {
  80322. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  80323. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  80324. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  80325. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  80326. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  80327. imageData[(x + width * y) * 4 + 0] = r;
  80328. imageData[(x + width * y) * 4 + 1] = g;
  80329. imageData[(x + width * y) * 4 + 2] = b;
  80330. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  80331. }
  80332. }
  80333. return imageData;
  80334. };
  80335. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80336. var image = pixel_data;
  80337. var width = header.width, height = header.height;
  80338. var i = 0, x, y;
  80339. var imageData = new Uint8Array(width * height * 4);
  80340. for (y = y_start; y !== y_end; y += y_step) {
  80341. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  80342. imageData[(x + width * y) * 4 + 3] = 255;
  80343. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80344. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  80345. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  80346. }
  80347. }
  80348. return imageData;
  80349. };
  80350. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80351. var image = pixel_data;
  80352. var width = header.width, height = header.height;
  80353. var i = 0, x, y;
  80354. var imageData = new Uint8Array(width * height * 4);
  80355. for (y = y_start; y !== y_end; y += y_step) {
  80356. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  80357. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80358. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  80359. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  80360. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  80361. }
  80362. }
  80363. return imageData;
  80364. };
  80365. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80366. var image = pixel_data;
  80367. var width = header.width, height = header.height;
  80368. var color, i = 0, x, y;
  80369. var imageData = new Uint8Array(width * height * 4);
  80370. for (y = y_start; y !== y_end; y += y_step) {
  80371. for (x = x_start; x !== x_end; x += x_step, i++) {
  80372. color = image[i];
  80373. imageData[(x + width * y) * 4 + 0] = color;
  80374. imageData[(x + width * y) * 4 + 1] = color;
  80375. imageData[(x + width * y) * 4 + 2] = color;
  80376. imageData[(x + width * y) * 4 + 3] = 255;
  80377. }
  80378. }
  80379. return imageData;
  80380. };
  80381. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80382. var image = pixel_data;
  80383. var width = header.width, height = header.height;
  80384. var i = 0, x, y;
  80385. var imageData = new Uint8Array(width * height * 4);
  80386. for (y = y_start; y !== y_end; y += y_step) {
  80387. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  80388. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  80389. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  80390. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80391. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  80392. }
  80393. }
  80394. return imageData;
  80395. };
  80396. //private static _TYPE_NO_DATA = 0;
  80397. TGATools._TYPE_INDEXED = 1;
  80398. TGATools._TYPE_RGB = 2;
  80399. TGATools._TYPE_GREY = 3;
  80400. TGATools._TYPE_RLE_INDEXED = 9;
  80401. TGATools._TYPE_RLE_RGB = 10;
  80402. TGATools._TYPE_RLE_GREY = 11;
  80403. TGATools._ORIGIN_MASK = 0x30;
  80404. TGATools._ORIGIN_SHIFT = 0x04;
  80405. TGATools._ORIGIN_BL = 0x00;
  80406. TGATools._ORIGIN_BR = 0x01;
  80407. TGATools._ORIGIN_UL = 0x02;
  80408. TGATools._ORIGIN_UR = 0x03;
  80409. return TGATools;
  80410. }());
  80411. BABYLON.TGATools = TGATools;
  80412. })(BABYLON || (BABYLON = {}));
  80413. //# sourceMappingURL=babylon.tga.js.map
  80414. "use strict";
  80415. var BABYLON;
  80416. (function (BABYLON) {
  80417. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  80418. // All values and structures referenced from:
  80419. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  80420. var DDS_MAGIC = 0x20534444;
  80421. var
  80422. //DDSD_CAPS = 0x1,
  80423. //DDSD_HEIGHT = 0x2,
  80424. //DDSD_WIDTH = 0x4,
  80425. //DDSD_PITCH = 0x8,
  80426. //DDSD_PIXELFORMAT = 0x1000,
  80427. DDSD_MIPMAPCOUNT = 0x20000;
  80428. //DDSD_LINEARSIZE = 0x80000,
  80429. //DDSD_DEPTH = 0x800000;
  80430. // var DDSCAPS_COMPLEX = 0x8,
  80431. // DDSCAPS_MIPMAP = 0x400000,
  80432. // DDSCAPS_TEXTURE = 0x1000;
  80433. var DDSCAPS2_CUBEMAP = 0x200;
  80434. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  80435. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  80436. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  80437. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  80438. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  80439. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  80440. // DDSCAPS2_VOLUME = 0x200000;
  80441. var
  80442. //DDPF_ALPHAPIXELS = 0x1,
  80443. //DDPF_ALPHA = 0x2,
  80444. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  80445. //DDPF_YUV = 0x200,
  80446. DDPF_LUMINANCE = 0x20000;
  80447. function FourCCToInt32(value) {
  80448. return value.charCodeAt(0) +
  80449. (value.charCodeAt(1) << 8) +
  80450. (value.charCodeAt(2) << 16) +
  80451. (value.charCodeAt(3) << 24);
  80452. }
  80453. function Int32ToFourCC(value) {
  80454. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  80455. }
  80456. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  80457. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  80458. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  80459. var FOURCC_DX10 = FourCCToInt32("DX10");
  80460. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  80461. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  80462. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  80463. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  80464. var headerLengthInt = 31; // The header length in 32 bit ints
  80465. // Offsets into the header array
  80466. var off_magic = 0;
  80467. var off_size = 1;
  80468. var off_flags = 2;
  80469. var off_height = 3;
  80470. var off_width = 4;
  80471. var off_mipmapCount = 7;
  80472. var off_pfFlags = 20;
  80473. var off_pfFourCC = 21;
  80474. var off_RGBbpp = 22;
  80475. var off_RMask = 23;
  80476. var off_GMask = 24;
  80477. var off_BMask = 25;
  80478. var off_AMask = 26;
  80479. // var off_caps1 = 27;
  80480. var off_caps2 = 28;
  80481. // var off_caps3 = 29;
  80482. // var off_caps4 = 30;
  80483. var off_dxgiFormat = 32;
  80484. ;
  80485. var DDSTools = /** @class */ (function () {
  80486. function DDSTools() {
  80487. }
  80488. DDSTools.GetDDSInfo = function (arrayBuffer) {
  80489. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80490. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  80491. var mipmapCount = 1;
  80492. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  80493. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80494. }
  80495. var fourCC = header[off_pfFourCC];
  80496. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  80497. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80498. switch (fourCC) {
  80499. case FOURCC_D3DFMT_R16G16B16A16F:
  80500. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80501. break;
  80502. case FOURCC_D3DFMT_R32G32B32A32F:
  80503. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80504. break;
  80505. case FOURCC_DX10:
  80506. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  80507. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80508. break;
  80509. }
  80510. }
  80511. return {
  80512. width: header[off_width],
  80513. height: header[off_height],
  80514. mipmapCount: mipmapCount,
  80515. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  80516. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  80517. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  80518. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  80519. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  80520. dxgiFormat: dxgiFormat,
  80521. textureType: textureType
  80522. };
  80523. };
  80524. DDSTools._ToHalfFloat = function (value) {
  80525. if (!DDSTools._FloatView) {
  80526. DDSTools._FloatView = new Float32Array(1);
  80527. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  80528. }
  80529. DDSTools._FloatView[0] = value;
  80530. var x = DDSTools._Int32View[0];
  80531. var bits = (x >> 16) & 0x8000; /* Get the sign */
  80532. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  80533. var e = (x >> 23) & 0xff; /* Using int is faster here */
  80534. /* If zero, or denormal, or exponent underflows too much for a denormal
  80535. * half, return signed zero. */
  80536. if (e < 103) {
  80537. return bits;
  80538. }
  80539. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  80540. if (e > 142) {
  80541. bits |= 0x7c00;
  80542. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  80543. * not Inf, so make sure we set one mantissa bit too. */
  80544. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  80545. return bits;
  80546. }
  80547. /* If exponent underflows but not too much, return a denormal */
  80548. if (e < 113) {
  80549. m |= 0x0800;
  80550. /* Extra rounding may overflow and set mantissa to 0 and exponent
  80551. * to 1, which is OK. */
  80552. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  80553. return bits;
  80554. }
  80555. bits |= ((e - 112) << 10) | (m >> 1);
  80556. bits += m & 1;
  80557. return bits;
  80558. };
  80559. DDSTools._FromHalfFloat = function (value) {
  80560. var s = (value & 0x8000) >> 15;
  80561. var e = (value & 0x7C00) >> 10;
  80562. var f = value & 0x03FF;
  80563. if (e === 0) {
  80564. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  80565. }
  80566. else if (e == 0x1F) {
  80567. return f ? NaN : ((s ? -1 : 1) * Infinity);
  80568. }
  80569. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  80570. };
  80571. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80572. var destArray = new Float32Array(dataLength);
  80573. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80574. var index = 0;
  80575. for (var y = 0; y < height; y++) {
  80576. for (var x = 0; x < width; x++) {
  80577. var srcPos = (x + y * width) * 4;
  80578. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  80579. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  80580. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  80581. if (DDSTools.StoreLODInAlphaChannel) {
  80582. destArray[index + 3] = lod;
  80583. }
  80584. else {
  80585. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  80586. }
  80587. index += 4;
  80588. }
  80589. }
  80590. return destArray;
  80591. };
  80592. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80593. if (DDSTools.StoreLODInAlphaChannel) {
  80594. var destArray = new Uint16Array(dataLength);
  80595. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80596. var index = 0;
  80597. for (var y = 0; y < height; y++) {
  80598. for (var x = 0; x < width; x++) {
  80599. var srcPos = (x + y * width) * 4;
  80600. destArray[index] = srcData[srcPos];
  80601. destArray[index + 1] = srcData[srcPos + 1];
  80602. destArray[index + 2] = srcData[srcPos + 2];
  80603. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  80604. index += 4;
  80605. }
  80606. }
  80607. return destArray;
  80608. }
  80609. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  80610. };
  80611. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80612. if (DDSTools.StoreLODInAlphaChannel) {
  80613. var destArray = new Float32Array(dataLength);
  80614. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80615. var index = 0;
  80616. for (var y = 0; y < height; y++) {
  80617. for (var x = 0; x < width; x++) {
  80618. var srcPos = (x + y * width) * 4;
  80619. destArray[index] = srcData[srcPos];
  80620. destArray[index + 1] = srcData[srcPos + 1];
  80621. destArray[index + 2] = srcData[srcPos + 2];
  80622. destArray[index + 3] = lod;
  80623. index += 4;
  80624. }
  80625. }
  80626. return destArray;
  80627. }
  80628. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  80629. };
  80630. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80631. var destArray = new Uint8Array(dataLength);
  80632. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80633. var index = 0;
  80634. for (var y = 0; y < height; y++) {
  80635. for (var x = 0; x < width; x++) {
  80636. var srcPos = (x + y * width) * 4;
  80637. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  80638. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  80639. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  80640. if (DDSTools.StoreLODInAlphaChannel) {
  80641. destArray[index + 3] = lod;
  80642. }
  80643. else {
  80644. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  80645. }
  80646. index += 4;
  80647. }
  80648. }
  80649. return destArray;
  80650. };
  80651. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80652. var destArray = new Uint8Array(dataLength);
  80653. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80654. var index = 0;
  80655. for (var y = 0; y < height; y++) {
  80656. for (var x = 0; x < width; x++) {
  80657. var srcPos = (x + y * width) * 4;
  80658. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  80659. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  80660. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  80661. if (DDSTools.StoreLODInAlphaChannel) {
  80662. destArray[index + 3] = lod;
  80663. }
  80664. else {
  80665. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  80666. }
  80667. index += 4;
  80668. }
  80669. }
  80670. return destArray;
  80671. };
  80672. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  80673. var byteArray = new Uint8Array(dataLength);
  80674. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80675. var index = 0;
  80676. for (var y = 0; y < height; y++) {
  80677. for (var x = 0; x < width; x++) {
  80678. var srcPos = (x + y * width) * 4;
  80679. byteArray[index] = srcData[srcPos + rOffset];
  80680. byteArray[index + 1] = srcData[srcPos + gOffset];
  80681. byteArray[index + 2] = srcData[srcPos + bOffset];
  80682. byteArray[index + 3] = srcData[srcPos + aOffset];
  80683. index += 4;
  80684. }
  80685. }
  80686. return byteArray;
  80687. };
  80688. DDSTools._ExtractLongWordOrder = function (value) {
  80689. if (value === 0 || value === 255 || value === -16777216) {
  80690. return 0;
  80691. }
  80692. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  80693. };
  80694. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  80695. var byteArray = new Uint8Array(dataLength);
  80696. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80697. var index = 0;
  80698. for (var y = 0; y < height; y++) {
  80699. for (var x = 0; x < width; x++) {
  80700. var srcPos = (x + y * width) * 3;
  80701. byteArray[index] = srcData[srcPos + rOffset];
  80702. byteArray[index + 1] = srcData[srcPos + gOffset];
  80703. byteArray[index + 2] = srcData[srcPos + bOffset];
  80704. index += 3;
  80705. }
  80706. }
  80707. return byteArray;
  80708. };
  80709. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  80710. var byteArray = new Uint8Array(dataLength);
  80711. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80712. var index = 0;
  80713. for (var y = 0; y < height; y++) {
  80714. for (var x = 0; x < width; x++) {
  80715. var srcPos = (x + y * width);
  80716. byteArray[index] = srcData[srcPos];
  80717. index++;
  80718. }
  80719. }
  80720. return byteArray;
  80721. };
  80722. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  80723. if (lodIndex === void 0) { lodIndex = -1; }
  80724. var ext = engine.getCaps().s3tc;
  80725. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80726. var fourCC, width, height, dataLength = 0, dataOffset;
  80727. var byteArray, mipmapCount, mip;
  80728. var internalFormat = 0;
  80729. var format = 0;
  80730. var blockBytes = 1;
  80731. if (header[off_magic] !== DDS_MAGIC) {
  80732. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80733. return;
  80734. }
  80735. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80736. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80737. return;
  80738. }
  80739. if (info.isCompressed && !ext) {
  80740. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80741. return;
  80742. }
  80743. var bpp = header[off_RGBbpp];
  80744. dataOffset = header[off_size] + 4;
  80745. var computeFormats = false;
  80746. if (info.isFourCC) {
  80747. fourCC = header[off_pfFourCC];
  80748. switch (fourCC) {
  80749. case FOURCC_DXT1:
  80750. blockBytes = 8;
  80751. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80752. break;
  80753. case FOURCC_DXT3:
  80754. blockBytes = 16;
  80755. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80756. break;
  80757. case FOURCC_DXT5:
  80758. blockBytes = 16;
  80759. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80760. break;
  80761. case FOURCC_D3DFMT_R16G16B16A16F:
  80762. computeFormats = true;
  80763. break;
  80764. case FOURCC_D3DFMT_R32G32B32A32F:
  80765. computeFormats = true;
  80766. break;
  80767. case FOURCC_DX10:
  80768. // There is an additionnal header so dataOffset need to be changed
  80769. dataOffset += 5 * 4; // 5 uints
  80770. var supported = false;
  80771. switch (info.dxgiFormat) {
  80772. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80773. computeFormats = true;
  80774. supported = true;
  80775. break;
  80776. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80777. info.isRGB = true;
  80778. info.isFourCC = false;
  80779. bpp = 32;
  80780. supported = true;
  80781. break;
  80782. }
  80783. if (supported) {
  80784. break;
  80785. }
  80786. default:
  80787. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80788. return;
  80789. }
  80790. }
  80791. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80792. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80793. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80794. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80795. if (computeFormats) {
  80796. format = engine._getWebGLTextureType(info.textureType);
  80797. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80798. }
  80799. mipmapCount = 1;
  80800. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80801. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80802. }
  80803. for (var face = 0; face < faces; face++) {
  80804. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80805. width = header[off_width];
  80806. height = header[off_height];
  80807. for (mip = 0; mip < mipmapCount; ++mip) {
  80808. if (lodIndex === -1 || lodIndex === mip) {
  80809. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80810. var i = (lodIndex === -1) ? mip : 0;
  80811. if (!info.isCompressed && info.isFourCC) {
  80812. dataLength = width * height * 4;
  80813. var floatArray = null;
  80814. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80815. if (bpp === 128) {
  80816. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80817. }
  80818. else if (bpp === 64) {
  80819. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80820. }
  80821. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80822. format = engine._getWebGLTextureType(info.textureType);
  80823. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80824. }
  80825. else {
  80826. if (bpp === 128) {
  80827. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80828. }
  80829. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80830. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80831. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80832. format = engine._getWebGLTextureType(info.textureType);
  80833. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80834. }
  80835. else {
  80836. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80837. }
  80838. }
  80839. if (floatArray) {
  80840. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80841. }
  80842. }
  80843. else if (info.isRGB) {
  80844. if (bpp === 24) {
  80845. dataLength = width * height * 3;
  80846. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80847. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80848. }
  80849. else {
  80850. dataLength = width * height * 4;
  80851. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80852. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80853. }
  80854. }
  80855. else if (info.isLuminance) {
  80856. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80857. var unpaddedRowSize = width;
  80858. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80859. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80860. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80861. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80862. }
  80863. else {
  80864. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80865. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80866. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80867. }
  80868. }
  80869. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80870. width *= 0.5;
  80871. height *= 0.5;
  80872. width = Math.max(1.0, width);
  80873. height = Math.max(1.0, height);
  80874. }
  80875. if (currentFace !== undefined) {
  80876. // Loading a single face
  80877. break;
  80878. }
  80879. }
  80880. };
  80881. DDSTools.StoreLODInAlphaChannel = false;
  80882. return DDSTools;
  80883. }());
  80884. BABYLON.DDSTools = DDSTools;
  80885. })(BABYLON || (BABYLON = {}));
  80886. //# sourceMappingURL=babylon.dds.js.map
  80887. "use strict";
  80888. var BABYLON;
  80889. (function (BABYLON) {
  80890. /**
  80891. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80892. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80893. */
  80894. var KhronosTextureContainer = /** @class */ (function () {
  80895. /**
  80896. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80897. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80898. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80899. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80900. */
  80901. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80902. this.arrayBuffer = arrayBuffer;
  80903. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80904. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80905. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80906. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80907. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80908. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80909. BABYLON.Tools.Error("texture missing KTX identifier");
  80910. return;
  80911. }
  80912. // load the reset of the header in native 32 bit int
  80913. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80914. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80915. var oppositeEndianess = header[0] === 0x01020304;
  80916. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80917. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80918. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80919. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80920. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80921. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80922. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80923. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80924. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80925. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80926. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80927. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80928. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80929. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80930. if (this.glType !== 0) {
  80931. BABYLON.Tools.Error("only compressed formats currently supported");
  80932. return;
  80933. }
  80934. else {
  80935. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80936. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80937. }
  80938. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80939. BABYLON.Tools.Error("only 2D textures currently supported");
  80940. return;
  80941. }
  80942. if (this.numberOfArrayElements !== 0) {
  80943. BABYLON.Tools.Error("texture arrays not currently supported");
  80944. return;
  80945. }
  80946. if (this.numberOfFaces !== facesExpected) {
  80947. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80948. return;
  80949. }
  80950. // we now have a completely validated file, so could use existence of loadType as success
  80951. // would need to make this more elaborate & adjust checks above to support more than one load type
  80952. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80953. }
  80954. // not as fast hardware based, but will probably never need to use
  80955. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80956. return ((val & 0xFF) << 24)
  80957. | ((val & 0xFF00) << 8)
  80958. | ((val >> 8) & 0xFF00)
  80959. | ((val >> 24) & 0xFF);
  80960. };
  80961. /**
  80962. * It is assumed that the texture has already been created & is currently bound
  80963. */
  80964. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80965. switch (this.loadType) {
  80966. case KhronosTextureContainer.COMPRESSED_2D:
  80967. this._upload2DCompressedLevels(gl, loadMipmaps);
  80968. break;
  80969. case KhronosTextureContainer.TEX_2D:
  80970. case KhronosTextureContainer.COMPRESSED_3D:
  80971. case KhronosTextureContainer.TEX_3D:
  80972. }
  80973. };
  80974. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80975. // initialize width & height for level 1
  80976. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80977. var width = this.pixelWidth;
  80978. var height = this.pixelHeight;
  80979. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80980. for (var level = 0; level < mipmapCount; level++) {
  80981. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80982. for (var face = 0; face < this.numberOfFaces; face++) {
  80983. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80984. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80985. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80986. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80987. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80988. }
  80989. width = Math.max(1.0, width * 0.5);
  80990. height = Math.max(1.0, height * 0.5);
  80991. }
  80992. };
  80993. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80994. // load types
  80995. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80996. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80997. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80998. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80999. return KhronosTextureContainer;
  81000. }());
  81001. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  81002. })(BABYLON || (BABYLON = {}));
  81003. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  81004. "use strict";
  81005. var BABYLON;
  81006. (function (BABYLON) {
  81007. var Debug = /** @class */ (function () {
  81008. function Debug() {
  81009. }
  81010. Debug.AxesViewer = /** @class */ (function () {
  81011. function AxesViewer(scene, scaleLines) {
  81012. if (scaleLines === void 0) { scaleLines = 1; }
  81013. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81014. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81015. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81016. this.scaleLines = 1;
  81017. this.scaleLines = scaleLines;
  81018. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  81019. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  81020. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  81021. this._xmesh.renderingGroupId = 2;
  81022. this._ymesh.renderingGroupId = 2;
  81023. this._zmesh.renderingGroupId = 2;
  81024. this._xmesh.material.checkReadyOnlyOnce = true;
  81025. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  81026. this._ymesh.material.checkReadyOnlyOnce = true;
  81027. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  81028. this._zmesh.material.checkReadyOnlyOnce = true;
  81029. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  81030. this.scene = scene;
  81031. }
  81032. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  81033. var scaleLines = this.scaleLines;
  81034. if (this._xmesh) {
  81035. this._xmesh.position.copyFrom(position);
  81036. }
  81037. if (this._ymesh) {
  81038. this._ymesh.position.copyFrom(position);
  81039. }
  81040. if (this._zmesh) {
  81041. this._zmesh.position.copyFrom(position);
  81042. }
  81043. var point2 = this._xline[1];
  81044. point2.x = xaxis.x * scaleLines;
  81045. point2.y = xaxis.y * scaleLines;
  81046. point2.z = xaxis.z * scaleLines;
  81047. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  81048. point2 = this._yline[1];
  81049. point2.x = yaxis.x * scaleLines;
  81050. point2.y = yaxis.y * scaleLines;
  81051. point2.z = yaxis.z * scaleLines;
  81052. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  81053. point2 = this._zline[1];
  81054. point2.x = zaxis.x * scaleLines;
  81055. point2.y = zaxis.y * scaleLines;
  81056. point2.z = zaxis.z * scaleLines;
  81057. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  81058. };
  81059. AxesViewer.prototype.dispose = function () {
  81060. if (this._xmesh) {
  81061. this._xmesh.dispose();
  81062. }
  81063. if (this._ymesh) {
  81064. this._ymesh.dispose();
  81065. }
  81066. if (this._zmesh) {
  81067. this._zmesh.dispose();
  81068. }
  81069. this._xmesh = null;
  81070. this._ymesh = null;
  81071. this._zmesh = null;
  81072. this.scene = null;
  81073. };
  81074. return AxesViewer;
  81075. }());
  81076. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  81077. __extends(BoneAxesViewer, _super);
  81078. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  81079. if (scaleLines === void 0) { scaleLines = 1; }
  81080. var _this = _super.call(this, scene, scaleLines) || this;
  81081. _this.pos = BABYLON.Vector3.Zero();
  81082. _this.xaxis = BABYLON.Vector3.Zero();
  81083. _this.yaxis = BABYLON.Vector3.Zero();
  81084. _this.zaxis = BABYLON.Vector3.Zero();
  81085. _this.mesh = mesh;
  81086. _this.bone = bone;
  81087. return _this;
  81088. }
  81089. BoneAxesViewer.prototype.update = function () {
  81090. if (!this.mesh || !this.bone) {
  81091. return;
  81092. }
  81093. var bone = this.bone;
  81094. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  81095. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  81096. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  81097. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  81098. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  81099. };
  81100. BoneAxesViewer.prototype.dispose = function () {
  81101. if (this.mesh) {
  81102. this.mesh = null;
  81103. this.bone = null;
  81104. _super.prototype.dispose.call(this);
  81105. }
  81106. };
  81107. return BoneAxesViewer;
  81108. }(Debug.AxesViewer));
  81109. Debug.PhysicsViewer = /** @class */ (function () {
  81110. function PhysicsViewer(scene) {
  81111. this._impostors = [];
  81112. this._meshes = [];
  81113. this._numMeshes = 0;
  81114. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81115. var physicEngine = this._scene.getPhysicsEngine();
  81116. if (physicEngine) {
  81117. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  81118. }
  81119. }
  81120. PhysicsViewer.prototype._updateDebugMeshes = function () {
  81121. var plugin = this._physicsEnginePlugin;
  81122. for (var i = 0; i < this._numMeshes; i++) {
  81123. var impostor = this._impostors[i];
  81124. if (!impostor) {
  81125. continue;
  81126. }
  81127. if (impostor.isDisposed) {
  81128. this.hideImpostor(this._impostors[i--]);
  81129. }
  81130. else {
  81131. var mesh = this._meshes[i];
  81132. if (mesh && plugin) {
  81133. plugin.syncMeshWithImpostor(mesh, impostor);
  81134. }
  81135. }
  81136. }
  81137. };
  81138. PhysicsViewer.prototype.showImpostor = function (impostor) {
  81139. if (!this._scene) {
  81140. return;
  81141. }
  81142. for (var i = 0; i < this._numMeshes; i++) {
  81143. if (this._impostors[i] == impostor) {
  81144. return;
  81145. }
  81146. }
  81147. var debugMesh = this._getDebugMesh(impostor, this._scene);
  81148. if (debugMesh) {
  81149. this._impostors[this._numMeshes] = impostor;
  81150. this._meshes[this._numMeshes] = debugMesh;
  81151. if (this._numMeshes === 0) {
  81152. this._renderFunction = this._updateDebugMeshes.bind(this);
  81153. this._scene.registerBeforeRender(this._renderFunction);
  81154. }
  81155. this._numMeshes++;
  81156. }
  81157. };
  81158. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  81159. if (!impostor || !this._scene) {
  81160. return;
  81161. }
  81162. var removed = false;
  81163. for (var i = 0; i < this._numMeshes; i++) {
  81164. if (this._impostors[i] == impostor) {
  81165. var mesh = this._meshes[i];
  81166. if (!mesh) {
  81167. continue;
  81168. }
  81169. this._scene.removeMesh(mesh);
  81170. mesh.dispose();
  81171. this._numMeshes--;
  81172. if (this._numMeshes > 0) {
  81173. this._meshes[i] = this._meshes[this._numMeshes];
  81174. this._impostors[i] = this._impostors[this._numMeshes];
  81175. this._meshes[this._numMeshes] = null;
  81176. this._impostors[this._numMeshes] = null;
  81177. }
  81178. else {
  81179. this._meshes[0] = null;
  81180. this._impostors[0] = null;
  81181. }
  81182. removed = true;
  81183. break;
  81184. }
  81185. }
  81186. if (removed && this._numMeshes === 0) {
  81187. this._scene.unregisterBeforeRender(this._renderFunction);
  81188. }
  81189. };
  81190. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  81191. if (!this._debugMaterial) {
  81192. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  81193. this._debugMaterial.wireframe = true;
  81194. }
  81195. return this._debugMaterial;
  81196. };
  81197. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  81198. if (!this._debugBoxMesh) {
  81199. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  81200. this._debugBoxMesh.renderingGroupId = 1;
  81201. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  81202. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  81203. scene.removeMesh(this._debugBoxMesh);
  81204. }
  81205. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  81206. };
  81207. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  81208. if (!this._debugSphereMesh) {
  81209. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  81210. this._debugSphereMesh.renderingGroupId = 1;
  81211. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  81212. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  81213. scene.removeMesh(this._debugSphereMesh);
  81214. }
  81215. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  81216. };
  81217. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  81218. var mesh = null;
  81219. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  81220. mesh = this._getDebugBoxMesh(scene);
  81221. impostor.getBoxSizeToRef(mesh.scaling);
  81222. }
  81223. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  81224. mesh = this._getDebugSphereMesh(scene);
  81225. var radius = impostor.getRadius();
  81226. mesh.scaling.x = radius * 2;
  81227. mesh.scaling.y = radius * 2;
  81228. mesh.scaling.z = radius * 2;
  81229. }
  81230. return mesh;
  81231. };
  81232. PhysicsViewer.prototype.dispose = function () {
  81233. for (var i = 0; i < this._numMeshes; i++) {
  81234. this.hideImpostor(this._impostors[i]);
  81235. }
  81236. if (this._debugBoxMesh) {
  81237. this._debugBoxMesh.dispose();
  81238. }
  81239. if (this._debugSphereMesh) {
  81240. this._debugSphereMesh.dispose();
  81241. }
  81242. if (this._debugMaterial) {
  81243. this._debugMaterial.dispose();
  81244. }
  81245. this._impostors.length = 0;
  81246. this._scene = null;
  81247. this._physicsEnginePlugin = null;
  81248. };
  81249. return PhysicsViewer;
  81250. }());
  81251. Debug.SkeletonViewer = /** @class */ (function () {
  81252. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  81253. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  81254. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  81255. this.skeleton = skeleton;
  81256. this.mesh = mesh;
  81257. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  81258. this.renderingGroupId = renderingGroupId;
  81259. this.color = BABYLON.Color3.White();
  81260. this._debugLines = new Array();
  81261. this._isEnabled = false;
  81262. this._scene = scene;
  81263. this.update();
  81264. this._renderFunction = this.update.bind(this);
  81265. }
  81266. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  81267. get: function () {
  81268. return this._isEnabled;
  81269. },
  81270. set: function (value) {
  81271. if (this._isEnabled === value) {
  81272. return;
  81273. }
  81274. this._isEnabled = value;
  81275. if (value) {
  81276. this._scene.registerBeforeRender(this._renderFunction);
  81277. }
  81278. else {
  81279. this._scene.unregisterBeforeRender(this._renderFunction);
  81280. }
  81281. },
  81282. enumerable: true,
  81283. configurable: true
  81284. });
  81285. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  81286. if (x === void 0) { x = 0; }
  81287. if (y === void 0) { y = 0; }
  81288. if (z === void 0) { z = 0; }
  81289. var tmat = BABYLON.Tmp.Matrix[0];
  81290. var parentBone = bone.getParent();
  81291. tmat.copyFrom(bone.getLocalMatrix());
  81292. if (x !== 0 || y !== 0 || z !== 0) {
  81293. var tmat2 = BABYLON.Tmp.Matrix[1];
  81294. BABYLON.Matrix.IdentityToRef(tmat2);
  81295. tmat2.m[12] = x;
  81296. tmat2.m[13] = y;
  81297. tmat2.m[14] = z;
  81298. tmat2.multiplyToRef(tmat, tmat);
  81299. }
  81300. if (parentBone) {
  81301. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  81302. }
  81303. tmat.multiplyToRef(meshMat, tmat);
  81304. position.x = tmat.m[12];
  81305. position.y = tmat.m[13];
  81306. position.z = tmat.m[14];
  81307. };
  81308. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  81309. var len = bones.length;
  81310. var meshPos = this.mesh.position;
  81311. for (var i = 0; i < len; i++) {
  81312. var bone = bones[i];
  81313. var points = this._debugLines[i];
  81314. if (!points) {
  81315. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81316. this._debugLines[i] = points;
  81317. }
  81318. this._getBonePosition(points[0], bone, meshMat);
  81319. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  81320. points[0].subtractInPlace(meshPos);
  81321. points[1].subtractInPlace(meshPos);
  81322. }
  81323. };
  81324. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  81325. var len = bones.length;
  81326. var boneNum = 0;
  81327. var meshPos = this.mesh.position;
  81328. for (var i = len - 1; i >= 0; i--) {
  81329. var childBone = bones[i];
  81330. var parentBone = childBone.getParent();
  81331. if (!parentBone) {
  81332. continue;
  81333. }
  81334. var points = this._debugLines[boneNum];
  81335. if (!points) {
  81336. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81337. this._debugLines[boneNum] = points;
  81338. }
  81339. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  81340. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  81341. points[0].subtractInPlace(meshPos);
  81342. points[1].subtractInPlace(meshPos);
  81343. boneNum++;
  81344. }
  81345. };
  81346. SkeletonViewer.prototype.update = function () {
  81347. if (this.autoUpdateBonesMatrices) {
  81348. this.skeleton.computeAbsoluteTransforms();
  81349. }
  81350. if (this.skeleton.bones[0].length === undefined) {
  81351. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  81352. }
  81353. else {
  81354. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  81355. }
  81356. if (!this._debugMesh) {
  81357. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  81358. this._debugMesh.renderingGroupId = this.renderingGroupId;
  81359. }
  81360. else {
  81361. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  81362. }
  81363. this._debugMesh.position.copyFrom(this.mesh.position);
  81364. this._debugMesh.color = this.color;
  81365. };
  81366. SkeletonViewer.prototype.dispose = function () {
  81367. if (this._debugMesh) {
  81368. this.isEnabled = false;
  81369. this._debugMesh.dispose();
  81370. this._debugMesh = null;
  81371. }
  81372. };
  81373. return SkeletonViewer;
  81374. }());
  81375. return Debug;
  81376. }());
  81377. BABYLON.Debug = Debug;
  81378. })(BABYLON || (BABYLON = {}));
  81379. //# sourceMappingURL=babylon.debugModules.js.map
  81380. "use strict";
  81381. var BABYLON;
  81382. (function (BABYLON) {
  81383. var RayHelper = /** @class */ (function () {
  81384. function RayHelper(ray) {
  81385. this.ray = ray;
  81386. }
  81387. RayHelper.CreateAndShow = function (ray, scene, color) {
  81388. var helper = new RayHelper(ray);
  81389. helper.show(scene, color);
  81390. return helper;
  81391. };
  81392. RayHelper.prototype.show = function (scene, color) {
  81393. if (!this._renderFunction && this.ray) {
  81394. var ray = this.ray;
  81395. this._renderFunction = this._render.bind(this);
  81396. this._scene = scene;
  81397. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  81398. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  81399. if (this._renderFunction) {
  81400. this._scene.registerBeforeRender(this._renderFunction);
  81401. }
  81402. }
  81403. if (color && this._renderLine) {
  81404. this._renderLine.color.copyFrom(color);
  81405. }
  81406. };
  81407. RayHelper.prototype.hide = function () {
  81408. if (this._renderFunction && this._scene) {
  81409. this._scene.unregisterBeforeRender(this._renderFunction);
  81410. this._scene = null;
  81411. this._renderFunction = null;
  81412. if (this._renderLine) {
  81413. this._renderLine.dispose();
  81414. this._renderLine = null;
  81415. }
  81416. this._renderPoints = [];
  81417. }
  81418. };
  81419. RayHelper.prototype._render = function () {
  81420. var ray = this.ray;
  81421. if (!ray) {
  81422. return;
  81423. }
  81424. var point = this._renderPoints[1];
  81425. var len = Math.min(ray.length, 1000000);
  81426. point.copyFrom(ray.direction);
  81427. point.scaleInPlace(len);
  81428. point.addInPlace(ray.origin);
  81429. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  81430. };
  81431. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  81432. this._attachedToMesh = mesh;
  81433. var ray = this.ray;
  81434. if (!ray) {
  81435. return;
  81436. }
  81437. if (!ray.direction) {
  81438. ray.direction = BABYLON.Vector3.Zero();
  81439. }
  81440. if (!ray.origin) {
  81441. ray.origin = BABYLON.Vector3.Zero();
  81442. }
  81443. if (length) {
  81444. ray.length = length;
  81445. }
  81446. if (!meshSpaceOrigin) {
  81447. meshSpaceOrigin = BABYLON.Vector3.Zero();
  81448. }
  81449. if (!meshSpaceDirection) {
  81450. // -1 so that this will work with Mesh.lookAt
  81451. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  81452. }
  81453. if (!this._meshSpaceDirection) {
  81454. this._meshSpaceDirection = meshSpaceDirection.clone();
  81455. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  81456. }
  81457. else {
  81458. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  81459. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  81460. }
  81461. if (!this._updateToMeshFunction) {
  81462. this._updateToMeshFunction = this._updateToMesh.bind(this);
  81463. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  81464. }
  81465. this._updateToMesh();
  81466. };
  81467. RayHelper.prototype.detachFromMesh = function () {
  81468. if (this._attachedToMesh) {
  81469. if (this._updateToMeshFunction) {
  81470. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  81471. }
  81472. this._attachedToMesh = null;
  81473. this._updateToMeshFunction = null;
  81474. }
  81475. };
  81476. RayHelper.prototype._updateToMesh = function () {
  81477. var ray = this.ray;
  81478. if (!this._attachedToMesh || !ray) {
  81479. return;
  81480. }
  81481. if (this._attachedToMesh._isDisposed) {
  81482. this.detachFromMesh();
  81483. return;
  81484. }
  81485. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  81486. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  81487. };
  81488. RayHelper.prototype.dispose = function () {
  81489. this.hide();
  81490. this.detachFromMesh();
  81491. this.ray = null;
  81492. };
  81493. return RayHelper;
  81494. }());
  81495. BABYLON.RayHelper = RayHelper;
  81496. })(BABYLON || (BABYLON = {}));
  81497. //# sourceMappingURL=babylon.rayHelper.js.map
  81498. "use strict";
  81499. var BABYLON;
  81500. (function (BABYLON) {
  81501. // load the inspector using require, if not present in the global namespace.
  81502. var DebugLayer = /** @class */ (function () {
  81503. function DebugLayer(scene) {
  81504. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81505. this._scene = scene;
  81506. // load inspector using require, if it doesn't exist on the global namespace.
  81507. }
  81508. /** Creates the inspector window. */
  81509. DebugLayer.prototype._createInspector = function (config) {
  81510. if (config === void 0) { config = {}; }
  81511. var popup = config.popup || false;
  81512. var initialTab = config.initialTab || 0;
  81513. var parentElement = config.parentElement || null;
  81514. if (!this._inspector) {
  81515. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81516. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  81517. } // else nothing to do,; instance is already existing
  81518. };
  81519. DebugLayer.prototype.isVisible = function () {
  81520. if (!this._inspector) {
  81521. return false;
  81522. }
  81523. return true;
  81524. };
  81525. DebugLayer.prototype.hide = function () {
  81526. if (this._inspector) {
  81527. try {
  81528. this._inspector.dispose();
  81529. }
  81530. catch (e) {
  81531. // If the inspector has been removed directly from the inspector tool
  81532. }
  81533. this._inspector = null;
  81534. }
  81535. };
  81536. DebugLayer.prototype.show = function (config) {
  81537. if (config === void 0) { config = {}; }
  81538. if (typeof this.BJSINSPECTOR == 'undefined') {
  81539. // Load inspector and add it to the DOM
  81540. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  81541. }
  81542. else {
  81543. // Otherwise creates the inspector
  81544. this._createInspector(config);
  81545. }
  81546. };
  81547. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  81548. return DebugLayer;
  81549. }());
  81550. BABYLON.DebugLayer = DebugLayer;
  81551. })(BABYLON || (BABYLON = {}));
  81552. //# sourceMappingURL=babylon.debugLayer.js.map
  81553. "use strict";
  81554. var BABYLON;
  81555. (function (BABYLON) {
  81556. var BoundingBoxRenderer = /** @class */ (function () {
  81557. function BoundingBoxRenderer(scene) {
  81558. this.frontColor = new BABYLON.Color3(1, 1, 1);
  81559. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  81560. this.showBackLines = true;
  81561. this.renderList = new BABYLON.SmartArray(32);
  81562. this._vertexBuffers = {};
  81563. this._scene = scene;
  81564. }
  81565. BoundingBoxRenderer.prototype._prepareRessources = function () {
  81566. if (this._colorShader) {
  81567. return;
  81568. }
  81569. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  81570. attributes: [BABYLON.VertexBuffer.PositionKind],
  81571. uniforms: ["world", "viewProjection", "color"]
  81572. });
  81573. var engine = this._scene.getEngine();
  81574. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  81575. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  81576. this._createIndexBuffer();
  81577. };
  81578. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  81579. var engine = this._scene.getEngine();
  81580. 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]);
  81581. };
  81582. BoundingBoxRenderer.prototype._rebuild = function () {
  81583. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81584. if (vb) {
  81585. vb._rebuild();
  81586. }
  81587. this._createIndexBuffer();
  81588. };
  81589. BoundingBoxRenderer.prototype.reset = function () {
  81590. this.renderList.reset();
  81591. };
  81592. BoundingBoxRenderer.prototype.render = function () {
  81593. if (this.renderList.length === 0) {
  81594. return;
  81595. }
  81596. this._prepareRessources();
  81597. if (!this._colorShader.isReady()) {
  81598. return;
  81599. }
  81600. var engine = this._scene.getEngine();
  81601. engine.setDepthWrite(false);
  81602. this._colorShader._preBind();
  81603. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  81604. var boundingBox = this.renderList.data[boundingBoxIndex];
  81605. var min = boundingBox.minimum;
  81606. var max = boundingBox.maximum;
  81607. var diff = max.subtract(min);
  81608. var median = min.add(diff.scale(0.5));
  81609. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81610. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81611. .multiply(boundingBox.getWorldMatrix());
  81612. // VBOs
  81613. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81614. if (this.showBackLines) {
  81615. // Back
  81616. engine.setDepthFunctionToGreaterOrEqual();
  81617. this._scene.resetCachedMaterial();
  81618. this._colorShader.setColor4("color", this.backColor.toColor4());
  81619. this._colorShader.bind(worldMatrix);
  81620. // Draw order
  81621. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81622. }
  81623. // Front
  81624. engine.setDepthFunctionToLess();
  81625. this._scene.resetCachedMaterial();
  81626. this._colorShader.setColor4("color", this.frontColor.toColor4());
  81627. this._colorShader.bind(worldMatrix);
  81628. // Draw order
  81629. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81630. }
  81631. this._colorShader.unbind();
  81632. engine.setDepthFunctionToLessOrEqual();
  81633. engine.setDepthWrite(true);
  81634. };
  81635. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  81636. this._prepareRessources();
  81637. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  81638. return;
  81639. }
  81640. var engine = this._scene.getEngine();
  81641. engine.setDepthWrite(false);
  81642. engine.setColorWrite(false);
  81643. this._colorShader._preBind();
  81644. var boundingBox = mesh._boundingInfo.boundingBox;
  81645. var min = boundingBox.minimum;
  81646. var max = boundingBox.maximum;
  81647. var diff = max.subtract(min);
  81648. var median = min.add(diff.scale(0.5));
  81649. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81650. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81651. .multiply(boundingBox.getWorldMatrix());
  81652. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81653. engine.setDepthFunctionToLess();
  81654. this._scene.resetCachedMaterial();
  81655. this._colorShader.bind(worldMatrix);
  81656. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81657. this._colorShader.unbind();
  81658. engine.setDepthFunctionToLessOrEqual();
  81659. engine.setDepthWrite(true);
  81660. engine.setColorWrite(true);
  81661. };
  81662. BoundingBoxRenderer.prototype.dispose = function () {
  81663. if (!this._colorShader) {
  81664. return;
  81665. }
  81666. this.renderList.dispose();
  81667. this._colorShader.dispose();
  81668. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81669. if (buffer) {
  81670. buffer.dispose();
  81671. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81672. }
  81673. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81674. };
  81675. return BoundingBoxRenderer;
  81676. }());
  81677. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  81678. })(BABYLON || (BABYLON = {}));
  81679. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  81680. "use strict";
  81681. var BABYLON;
  81682. (function (BABYLON) {
  81683. var MorphTarget = /** @class */ (function () {
  81684. function MorphTarget(name, influence) {
  81685. if (influence === void 0) { influence = 0; }
  81686. this.name = name;
  81687. this.animations = new Array();
  81688. this._positions = null;
  81689. this._normals = null;
  81690. this._tangents = null;
  81691. this.onInfluenceChanged = new BABYLON.Observable();
  81692. this.influence = influence;
  81693. }
  81694. Object.defineProperty(MorphTarget.prototype, "influence", {
  81695. get: function () {
  81696. return this._influence;
  81697. },
  81698. set: function (influence) {
  81699. if (this._influence === influence) {
  81700. return;
  81701. }
  81702. var previous = this._influence;
  81703. this._influence = influence;
  81704. if (this.onInfluenceChanged.hasObservers) {
  81705. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  81706. }
  81707. },
  81708. enumerable: true,
  81709. configurable: true
  81710. });
  81711. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  81712. get: function () {
  81713. return !!this._positions;
  81714. },
  81715. enumerable: true,
  81716. configurable: true
  81717. });
  81718. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  81719. get: function () {
  81720. return !!this._normals;
  81721. },
  81722. enumerable: true,
  81723. configurable: true
  81724. });
  81725. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  81726. get: function () {
  81727. return !!this._tangents;
  81728. },
  81729. enumerable: true,
  81730. configurable: true
  81731. });
  81732. MorphTarget.prototype.setPositions = function (data) {
  81733. this._positions = data;
  81734. };
  81735. MorphTarget.prototype.getPositions = function () {
  81736. return this._positions;
  81737. };
  81738. MorphTarget.prototype.setNormals = function (data) {
  81739. this._normals = data;
  81740. };
  81741. MorphTarget.prototype.getNormals = function () {
  81742. return this._normals;
  81743. };
  81744. MorphTarget.prototype.setTangents = function (data) {
  81745. this._tangents = data;
  81746. };
  81747. MorphTarget.prototype.getTangents = function () {
  81748. return this._tangents;
  81749. };
  81750. /**
  81751. * Serializes the current target into a Serialization object.
  81752. * Returns the serialized object.
  81753. */
  81754. MorphTarget.prototype.serialize = function () {
  81755. var serializationObject = {};
  81756. serializationObject.name = this.name;
  81757. serializationObject.influence = this.influence;
  81758. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81759. if (this.hasNormals) {
  81760. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81761. }
  81762. if (this.hasTangents) {
  81763. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81764. }
  81765. // Animations
  81766. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81767. return serializationObject;
  81768. };
  81769. // Statics
  81770. MorphTarget.Parse = function (serializationObject) {
  81771. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81772. result.setPositions(serializationObject.positions);
  81773. if (serializationObject.normals) {
  81774. result.setNormals(serializationObject.normals);
  81775. }
  81776. if (serializationObject.tangents) {
  81777. result.setTangents(serializationObject.tangents);
  81778. }
  81779. // Animations
  81780. if (serializationObject.animations) {
  81781. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81782. var parsedAnimation = serializationObject.animations[animationIndex];
  81783. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81784. }
  81785. }
  81786. return result;
  81787. };
  81788. MorphTarget.FromMesh = function (mesh, name, influence) {
  81789. if (!name) {
  81790. name = mesh.name;
  81791. }
  81792. var result = new MorphTarget(name, influence);
  81793. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81795. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81796. }
  81797. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81798. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81799. }
  81800. return result;
  81801. };
  81802. return MorphTarget;
  81803. }());
  81804. BABYLON.MorphTarget = MorphTarget;
  81805. })(BABYLON || (BABYLON = {}));
  81806. //# sourceMappingURL=babylon.morphTarget.js.map
  81807. "use strict";
  81808. var BABYLON;
  81809. (function (BABYLON) {
  81810. var MorphTargetManager = /** @class */ (function () {
  81811. function MorphTargetManager(scene) {
  81812. if (scene === void 0) { scene = null; }
  81813. this._targets = new Array();
  81814. this._targetObservable = new Array();
  81815. this._activeTargets = new BABYLON.SmartArray(16);
  81816. this._supportsNormals = false;
  81817. this._supportsTangents = false;
  81818. this._vertexCount = 0;
  81819. this._uniqueId = 0;
  81820. this._tempInfluences = new Array();
  81821. if (!scene) {
  81822. scene = BABYLON.Engine.LastCreatedScene;
  81823. }
  81824. this._scene = scene;
  81825. if (this._scene) {
  81826. this._scene.morphTargetManagers.push(this);
  81827. this._uniqueId = this._scene.getUniqueId();
  81828. }
  81829. }
  81830. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81831. get: function () {
  81832. return this._uniqueId;
  81833. },
  81834. enumerable: true,
  81835. configurable: true
  81836. });
  81837. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81838. get: function () {
  81839. return this._vertexCount;
  81840. },
  81841. enumerable: true,
  81842. configurable: true
  81843. });
  81844. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81845. get: function () {
  81846. return this._supportsNormals;
  81847. },
  81848. enumerable: true,
  81849. configurable: true
  81850. });
  81851. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81852. get: function () {
  81853. return this._supportsTangents;
  81854. },
  81855. enumerable: true,
  81856. configurable: true
  81857. });
  81858. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81859. get: function () {
  81860. return this._targets.length;
  81861. },
  81862. enumerable: true,
  81863. configurable: true
  81864. });
  81865. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81866. get: function () {
  81867. return this._activeTargets.length;
  81868. },
  81869. enumerable: true,
  81870. configurable: true
  81871. });
  81872. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81873. get: function () {
  81874. return this._influences;
  81875. },
  81876. enumerable: true,
  81877. configurable: true
  81878. });
  81879. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81880. return this._activeTargets.data[index];
  81881. };
  81882. MorphTargetManager.prototype.getTarget = function (index) {
  81883. return this._targets[index];
  81884. };
  81885. MorphTargetManager.prototype.addTarget = function (target) {
  81886. var _this = this;
  81887. this._targets.push(target);
  81888. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81889. _this._syncActiveTargets(needUpdate);
  81890. }));
  81891. this._syncActiveTargets(true);
  81892. };
  81893. MorphTargetManager.prototype.removeTarget = function (target) {
  81894. var index = this._targets.indexOf(target);
  81895. if (index >= 0) {
  81896. this._targets.splice(index, 1);
  81897. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81898. this._syncActiveTargets(true);
  81899. }
  81900. };
  81901. /**
  81902. * Serializes the current manager into a Serialization object.
  81903. * Returns the serialized object.
  81904. */
  81905. MorphTargetManager.prototype.serialize = function () {
  81906. var serializationObject = {};
  81907. serializationObject.id = this.uniqueId;
  81908. serializationObject.targets = [];
  81909. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81910. var target = _a[_i];
  81911. serializationObject.targets.push(target.serialize());
  81912. }
  81913. return serializationObject;
  81914. };
  81915. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81916. var influenceCount = 0;
  81917. this._activeTargets.reset();
  81918. this._supportsNormals = true;
  81919. this._supportsTangents = true;
  81920. this._vertexCount = 0;
  81921. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81922. var target = _a[_i];
  81923. this._activeTargets.push(target);
  81924. this._tempInfluences[influenceCount++] = target.influence;
  81925. var positions = target.getPositions();
  81926. if (positions) {
  81927. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81928. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81929. var vertexCount = positions.length / 3;
  81930. if (this._vertexCount === 0) {
  81931. this._vertexCount = vertexCount;
  81932. }
  81933. else if (this._vertexCount !== vertexCount) {
  81934. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81935. return;
  81936. }
  81937. }
  81938. }
  81939. if (!this._influences || this._influences.length !== influenceCount) {
  81940. this._influences = new Float32Array(influenceCount);
  81941. }
  81942. for (var index = 0; index < influenceCount; index++) {
  81943. this._influences[index] = this._tempInfluences[index];
  81944. }
  81945. if (needUpdate && this._scene) {
  81946. // Flag meshes as dirty to resync with the active targets
  81947. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81948. var mesh = _c[_b];
  81949. if (mesh.morphTargetManager === this) {
  81950. mesh._syncGeometryWithMorphTargetManager();
  81951. }
  81952. }
  81953. }
  81954. };
  81955. // Statics
  81956. MorphTargetManager.Parse = function (serializationObject, scene) {
  81957. var result = new MorphTargetManager(scene);
  81958. result._uniqueId = serializationObject.id;
  81959. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81960. var targetData = _a[_i];
  81961. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81962. }
  81963. return result;
  81964. };
  81965. return MorphTargetManager;
  81966. }());
  81967. BABYLON.MorphTargetManager = MorphTargetManager;
  81968. })(BABYLON || (BABYLON = {}));
  81969. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81970. "use strict";
  81971. var BABYLON;
  81972. (function (BABYLON) {
  81973. var Octree = /** @class */ (function () {
  81974. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81975. if (maxDepth === void 0) { maxDepth = 2; }
  81976. this.maxDepth = maxDepth;
  81977. this.dynamicContent = new Array();
  81978. this._maxBlockCapacity = maxBlockCapacity || 64;
  81979. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81980. this._creationFunc = creationFunc;
  81981. }
  81982. // Methods
  81983. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81984. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81985. };
  81986. Octree.prototype.addMesh = function (entry) {
  81987. for (var index = 0; index < this.blocks.length; index++) {
  81988. var block = this.blocks[index];
  81989. block.addEntry(entry);
  81990. }
  81991. };
  81992. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81993. this._selectionContent.reset();
  81994. for (var index = 0; index < this.blocks.length; index++) {
  81995. var block = this.blocks[index];
  81996. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81997. }
  81998. if (allowDuplicate) {
  81999. this._selectionContent.concat(this.dynamicContent);
  82000. }
  82001. else {
  82002. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  82003. }
  82004. return this._selectionContent;
  82005. };
  82006. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  82007. this._selectionContent.reset();
  82008. for (var index = 0; index < this.blocks.length; index++) {
  82009. var block = this.blocks[index];
  82010. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  82011. }
  82012. if (allowDuplicate) {
  82013. this._selectionContent.concat(this.dynamicContent);
  82014. }
  82015. else {
  82016. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  82017. }
  82018. return this._selectionContent;
  82019. };
  82020. Octree.prototype.intersectsRay = function (ray) {
  82021. this._selectionContent.reset();
  82022. for (var index = 0; index < this.blocks.length; index++) {
  82023. var block = this.blocks[index];
  82024. block.intersectsRay(ray, this._selectionContent);
  82025. }
  82026. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  82027. return this._selectionContent;
  82028. };
  82029. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  82030. target.blocks = new Array();
  82031. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  82032. // Segmenting space
  82033. for (var x = 0; x < 2; x++) {
  82034. for (var y = 0; y < 2; y++) {
  82035. for (var z = 0; z < 2; z++) {
  82036. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  82037. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  82038. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  82039. block.addEntries(entries);
  82040. target.blocks.push(block);
  82041. }
  82042. }
  82043. }
  82044. };
  82045. Octree.CreationFuncForMeshes = function (entry, block) {
  82046. var boundingInfo = entry.getBoundingInfo();
  82047. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  82048. block.entries.push(entry);
  82049. }
  82050. };
  82051. Octree.CreationFuncForSubMeshes = function (entry, block) {
  82052. var boundingInfo = entry.getBoundingInfo();
  82053. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  82054. block.entries.push(entry);
  82055. }
  82056. };
  82057. return Octree;
  82058. }());
  82059. BABYLON.Octree = Octree;
  82060. })(BABYLON || (BABYLON = {}));
  82061. //# sourceMappingURL=babylon.octree.js.map
  82062. "use strict";
  82063. var BABYLON;
  82064. (function (BABYLON) {
  82065. var OctreeBlock = /** @class */ (function () {
  82066. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  82067. this.entries = new Array();
  82068. this._boundingVectors = new Array();
  82069. this._capacity = capacity;
  82070. this._depth = depth;
  82071. this._maxDepth = maxDepth;
  82072. this._creationFunc = creationFunc;
  82073. this._minPoint = minPoint;
  82074. this._maxPoint = maxPoint;
  82075. this._boundingVectors.push(minPoint.clone());
  82076. this._boundingVectors.push(maxPoint.clone());
  82077. this._boundingVectors.push(minPoint.clone());
  82078. this._boundingVectors[2].x = maxPoint.x;
  82079. this._boundingVectors.push(minPoint.clone());
  82080. this._boundingVectors[3].y = maxPoint.y;
  82081. this._boundingVectors.push(minPoint.clone());
  82082. this._boundingVectors[4].z = maxPoint.z;
  82083. this._boundingVectors.push(maxPoint.clone());
  82084. this._boundingVectors[5].z = minPoint.z;
  82085. this._boundingVectors.push(maxPoint.clone());
  82086. this._boundingVectors[6].x = minPoint.x;
  82087. this._boundingVectors.push(maxPoint.clone());
  82088. this._boundingVectors[7].y = minPoint.y;
  82089. }
  82090. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  82091. // Property
  82092. get: function () {
  82093. return this._capacity;
  82094. },
  82095. enumerable: true,
  82096. configurable: true
  82097. });
  82098. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  82099. get: function () {
  82100. return this._minPoint;
  82101. },
  82102. enumerable: true,
  82103. configurable: true
  82104. });
  82105. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  82106. get: function () {
  82107. return this._maxPoint;
  82108. },
  82109. enumerable: true,
  82110. configurable: true
  82111. });
  82112. // Methods
  82113. OctreeBlock.prototype.addEntry = function (entry) {
  82114. if (this.blocks) {
  82115. for (var index = 0; index < this.blocks.length; index++) {
  82116. var block = this.blocks[index];
  82117. block.addEntry(entry);
  82118. }
  82119. return;
  82120. }
  82121. this._creationFunc(entry, this);
  82122. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  82123. this.createInnerBlocks();
  82124. }
  82125. };
  82126. OctreeBlock.prototype.addEntries = function (entries) {
  82127. for (var index = 0; index < entries.length; index++) {
  82128. var mesh = entries[index];
  82129. this.addEntry(mesh);
  82130. }
  82131. };
  82132. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  82133. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  82134. if (this.blocks) {
  82135. for (var index = 0; index < this.blocks.length; index++) {
  82136. var block = this.blocks[index];
  82137. block.select(frustumPlanes, selection, allowDuplicate);
  82138. }
  82139. return;
  82140. }
  82141. if (allowDuplicate) {
  82142. selection.concat(this.entries);
  82143. }
  82144. else {
  82145. selection.concatWithNoDuplicate(this.entries);
  82146. }
  82147. }
  82148. };
  82149. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  82150. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  82151. if (this.blocks) {
  82152. for (var index = 0; index < this.blocks.length; index++) {
  82153. var block = this.blocks[index];
  82154. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  82155. }
  82156. return;
  82157. }
  82158. if (allowDuplicate) {
  82159. selection.concat(this.entries);
  82160. }
  82161. else {
  82162. selection.concatWithNoDuplicate(this.entries);
  82163. }
  82164. }
  82165. };
  82166. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  82167. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  82168. if (this.blocks) {
  82169. for (var index = 0; index < this.blocks.length; index++) {
  82170. var block = this.blocks[index];
  82171. block.intersectsRay(ray, selection);
  82172. }
  82173. return;
  82174. }
  82175. selection.concatWithNoDuplicate(this.entries);
  82176. }
  82177. };
  82178. OctreeBlock.prototype.createInnerBlocks = function () {
  82179. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  82180. };
  82181. return OctreeBlock;
  82182. }());
  82183. BABYLON.OctreeBlock = OctreeBlock;
  82184. })(BABYLON || (BABYLON = {}));
  82185. //# sourceMappingURL=babylon.octreeBlock.js.map
  82186. "use strict";
  82187. var BABYLON;
  82188. (function (BABYLON) {
  82189. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  82190. __extends(VRDistortionCorrectionPostProcess, _super);
  82191. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  82192. var _this = _super.call(this, name, "vrDistortionCorrection", [
  82193. 'LensCenter',
  82194. 'Scale',
  82195. 'ScaleIn',
  82196. 'HmdWarpParam'
  82197. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  82198. _this._isRightEye = isRightEye;
  82199. _this._distortionFactors = vrMetrics.distortionK;
  82200. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  82201. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  82202. _this.adaptScaleToCurrentViewport = true;
  82203. _this.onSizeChangedObservable.add(function () {
  82204. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  82205. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  82206. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  82207. });
  82208. _this.onApplyObservable.add(function (effect) {
  82209. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  82210. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  82211. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  82212. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  82213. });
  82214. return _this;
  82215. }
  82216. return VRDistortionCorrectionPostProcess;
  82217. }(BABYLON.PostProcess));
  82218. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  82219. })(BABYLON || (BABYLON = {}));
  82220. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  82221. "use strict";
  82222. var BABYLON;
  82223. (function (BABYLON) {
  82224. var AnaglyphPostProcess = /** @class */ (function (_super) {
  82225. __extends(AnaglyphPostProcess, _super);
  82226. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  82227. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  82228. _this._passedProcess = rigCameras[0]._rigPostProcess;
  82229. _this.onApplyObservable.add(function (effect) {
  82230. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  82231. });
  82232. return _this;
  82233. }
  82234. return AnaglyphPostProcess;
  82235. }(BABYLON.PostProcess));
  82236. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  82237. })(BABYLON || (BABYLON = {}));
  82238. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  82239. "use strict";
  82240. var BABYLON;
  82241. (function (BABYLON) {
  82242. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  82243. __extends(StereoscopicInterlacePostProcess, _super);
  82244. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  82245. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  82246. _this._passedProcess = rigCameras[0]._rigPostProcess;
  82247. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  82248. _this.onSizeChangedObservable.add(function () {
  82249. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  82250. });
  82251. _this.onApplyObservable.add(function (effect) {
  82252. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  82253. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  82254. });
  82255. return _this;
  82256. }
  82257. return StereoscopicInterlacePostProcess;
  82258. }(BABYLON.PostProcess));
  82259. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  82260. })(BABYLON || (BABYLON = {}));
  82261. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  82262. "use strict";
  82263. var BABYLON;
  82264. (function (BABYLON) {
  82265. /**
  82266. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  82267. * Screen rotation is taken into account.
  82268. */
  82269. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  82270. function FreeCameraDeviceOrientationInput() {
  82271. var _this = this;
  82272. this._screenOrientationAngle = 0;
  82273. this._screenQuaternion = new BABYLON.Quaternion();
  82274. this._alpha = 0;
  82275. this._beta = 0;
  82276. this._gamma = 0;
  82277. this._orientationChanged = function () {
  82278. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  82279. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  82280. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  82281. };
  82282. this._deviceOrientation = function (evt) {
  82283. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  82284. _this._beta = evt.beta !== null ? evt.beta : 0;
  82285. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  82286. };
  82287. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  82288. this._orientationChanged();
  82289. }
  82290. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  82291. get: function () {
  82292. return this._camera;
  82293. },
  82294. set: function (camera) {
  82295. this._camera = camera;
  82296. if (this._camera != null && !this._camera.rotationQuaternion) {
  82297. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  82298. }
  82299. },
  82300. enumerable: true,
  82301. configurable: true
  82302. });
  82303. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  82304. window.addEventListener("orientationchange", this._orientationChanged);
  82305. window.addEventListener("deviceorientation", this._deviceOrientation);
  82306. //In certain cases, the attach control is called AFTER orientation was changed,
  82307. //So this is needed.
  82308. this._orientationChanged();
  82309. };
  82310. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  82311. window.removeEventListener("orientationchange", this._orientationChanged);
  82312. window.removeEventListener("deviceorientation", this._deviceOrientation);
  82313. };
  82314. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  82315. //if no device orientation provided, don't update the rotation.
  82316. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  82317. if (!this._alpha)
  82318. return;
  82319. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  82320. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  82321. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  82322. //Mirror on XY Plane
  82323. this._camera.rotationQuaternion.z *= -1;
  82324. this._camera.rotationQuaternion.w *= -1;
  82325. };
  82326. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  82327. return "FreeCameraDeviceOrientationInput";
  82328. };
  82329. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  82330. return "deviceOrientation";
  82331. };
  82332. return FreeCameraDeviceOrientationInput;
  82333. }());
  82334. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  82335. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  82336. })(BABYLON || (BABYLON = {}));
  82337. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  82338. "use strict";
  82339. var BABYLON;
  82340. (function (BABYLON) {
  82341. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  82342. function ArcRotateCameraVRDeviceOrientationInput() {
  82343. this.alphaCorrection = 1;
  82344. this.betaCorrection = 1;
  82345. this.gammaCorrection = 1;
  82346. this._alpha = 0;
  82347. this._gamma = 0;
  82348. this._dirty = false;
  82349. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  82350. }
  82351. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  82352. this.camera.attachControl(element, noPreventDefault);
  82353. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  82354. };
  82355. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  82356. if (evt.alpha !== null) {
  82357. this._alpha = +evt.alpha | 0;
  82358. }
  82359. if (evt.gamma !== null) {
  82360. this._gamma = +evt.gamma | 0;
  82361. }
  82362. this._dirty = true;
  82363. };
  82364. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  82365. if (this._dirty) {
  82366. this._dirty = false;
  82367. if (this._gamma < 0) {
  82368. this._gamma = 180 + this._gamma;
  82369. }
  82370. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  82371. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  82372. }
  82373. };
  82374. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  82375. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  82376. };
  82377. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  82378. return "ArcRotateCameraVRDeviceOrientationInput";
  82379. };
  82380. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  82381. return "VRDeviceOrientation";
  82382. };
  82383. return ArcRotateCameraVRDeviceOrientationInput;
  82384. }());
  82385. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  82386. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  82387. })(BABYLON || (BABYLON = {}));
  82388. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  82389. "use strict";
  82390. var BABYLON;
  82391. (function (BABYLON) {
  82392. var VRCameraMetrics = /** @class */ (function () {
  82393. function VRCameraMetrics() {
  82394. this.compensateDistortion = true;
  82395. }
  82396. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  82397. get: function () {
  82398. return this.hResolution / (2 * this.vResolution);
  82399. },
  82400. enumerable: true,
  82401. configurable: true
  82402. });
  82403. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  82404. get: function () {
  82405. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  82406. },
  82407. enumerable: true,
  82408. configurable: true
  82409. });
  82410. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  82411. get: function () {
  82412. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  82413. var h = (4 * meters) / this.hScreenSize;
  82414. return BABYLON.Matrix.Translation(h, 0, 0);
  82415. },
  82416. enumerable: true,
  82417. configurable: true
  82418. });
  82419. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  82420. get: function () {
  82421. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  82422. var h = (4 * meters) / this.hScreenSize;
  82423. return BABYLON.Matrix.Translation(-h, 0, 0);
  82424. },
  82425. enumerable: true,
  82426. configurable: true
  82427. });
  82428. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  82429. get: function () {
  82430. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  82431. },
  82432. enumerable: true,
  82433. configurable: true
  82434. });
  82435. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  82436. get: function () {
  82437. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  82438. },
  82439. enumerable: true,
  82440. configurable: true
  82441. });
  82442. VRCameraMetrics.GetDefault = function () {
  82443. var result = new VRCameraMetrics();
  82444. result.hResolution = 1280;
  82445. result.vResolution = 800;
  82446. result.hScreenSize = 0.149759993;
  82447. result.vScreenSize = 0.0935999975;
  82448. result.vScreenCenter = 0.0467999987;
  82449. result.eyeToScreenDistance = 0.0410000011;
  82450. result.lensSeparationDistance = 0.0635000020;
  82451. result.interpupillaryDistance = 0.0640000030;
  82452. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  82453. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  82454. result.postProcessScaleFactor = 1.714605507808412;
  82455. result.lensCenterOffset = 0.151976421;
  82456. return result;
  82457. };
  82458. return VRCameraMetrics;
  82459. }());
  82460. BABYLON.VRCameraMetrics = VRCameraMetrics;
  82461. })(BABYLON || (BABYLON = {}));
  82462. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  82463. "use strict";
  82464. var BABYLON;
  82465. (function (BABYLON) {
  82466. /**
  82467. * This represents a WebVR camera.
  82468. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  82469. * @example http://doc.babylonjs.com/how_to/webvr_camera
  82470. */
  82471. var WebVRFreeCamera = /** @class */ (function (_super) {
  82472. __extends(WebVRFreeCamera, _super);
  82473. /**
  82474. * Instantiates a WebVRFreeCamera.
  82475. * @param name The name of the WebVRFreeCamera
  82476. * @param position The starting anchor position for the camera
  82477. * @param scene The scene the camera belongs to
  82478. * @param webVROptions a set of customizable options for the webVRCamera
  82479. */
  82480. function WebVRFreeCamera(name, position, scene, webVROptions) {
  82481. if (webVROptions === void 0) { webVROptions = {}; }
  82482. var _this = _super.call(this, name, position, scene) || this;
  82483. _this.webVROptions = webVROptions;
  82484. /**
  82485. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  82486. */
  82487. _this._vrDevice = null;
  82488. /**
  82489. * The rawPose of the vrDevice.
  82490. */
  82491. _this.rawPose = null;
  82492. _this._specsVersion = "1.1";
  82493. _this._attached = false;
  82494. _this._descendants = [];
  82495. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82496. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82497. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  82498. _this._standingMatrix = null;
  82499. /**
  82500. * Represents device position in babylon space.
  82501. */
  82502. _this.devicePosition = BABYLON.Vector3.Zero();
  82503. /**
  82504. * Represents device rotation in babylon space.
  82505. */
  82506. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  82507. /**
  82508. * The scale of the device to be used when translating from device space to babylon space.
  82509. */
  82510. _this.deviceScaleFactor = 1;
  82511. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82512. _this._worldToDevice = BABYLON.Matrix.Identity();
  82513. /**
  82514. * References to the webVR controllers for the vrDevice.
  82515. */
  82516. _this.controllers = [];
  82517. /**
  82518. * Emits an event when a controller is attached.
  82519. */
  82520. _this.onControllersAttachedObservable = new BABYLON.Observable();
  82521. /**
  82522. * Emits an event when a controller's mesh has been loaded;
  82523. */
  82524. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82525. /**
  82526. * If the rig cameras be used as parent instead of this camera.
  82527. */
  82528. _this.rigParenting = true;
  82529. _this._defaultHeight = undefined;
  82530. _this._workingVector = BABYLON.Vector3.Zero();
  82531. _this._oneVector = BABYLON.Vector3.One();
  82532. _this._workingMatrix = BABYLON.Matrix.Identity();
  82533. _this._cache.position = BABYLON.Vector3.Zero();
  82534. if (webVROptions.defaultHeight) {
  82535. _this._defaultHeight = webVROptions.defaultHeight;
  82536. _this.position.y = _this._defaultHeight;
  82537. }
  82538. _this.minZ = 0.1;
  82539. //legacy support - the compensation boolean was removed.
  82540. if (arguments.length === 5) {
  82541. _this.webVROptions = arguments[4];
  82542. }
  82543. // default webVR options
  82544. if (_this.webVROptions.trackPosition == undefined) {
  82545. _this.webVROptions.trackPosition = true;
  82546. }
  82547. if (_this.webVROptions.controllerMeshes == undefined) {
  82548. _this.webVROptions.controllerMeshes = true;
  82549. }
  82550. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  82551. _this.webVROptions.defaultLightingOnControllers = true;
  82552. }
  82553. _this.rotationQuaternion = new BABYLON.Quaternion();
  82554. if (_this.webVROptions && _this.webVROptions.positionScale) {
  82555. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  82556. }
  82557. //enable VR
  82558. var engine = _this.getEngine();
  82559. _this._onVREnabled = function (success) { if (success) {
  82560. _this.initControllers();
  82561. } };
  82562. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  82563. engine.initWebVR().add(function (event) {
  82564. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  82565. return;
  82566. }
  82567. _this._vrDevice = event.vrDisplay;
  82568. //reset the rig parameters.
  82569. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  82570. if (_this._attached) {
  82571. _this.getEngine().enableVR();
  82572. }
  82573. });
  82574. if (typeof (VRFrameData) !== "undefined")
  82575. _this._frameData = new VRFrameData();
  82576. /**
  82577. * The idea behind the following lines:
  82578. * objects that have the camera as parent should actually have the rig cameras as a parent.
  82579. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  82580. * the second will not show it correctly.
  82581. *
  82582. * To solve this - each object that has the camera as parent will be added to a protected array.
  82583. * When the rig camera renders, it will take this array and set all of those to be its children.
  82584. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  82585. * Amazing!
  82586. */
  82587. scene.onBeforeCameraRenderObservable.add(function (camera) {
  82588. if (camera.parent === _this && _this.rigParenting) {
  82589. _this._descendants = _this.getDescendants(true, function (n) {
  82590. // don't take the cameras or the controllers!
  82591. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  82592. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  82593. return !isController && !isRigCamera;
  82594. });
  82595. _this._descendants.forEach(function (node) {
  82596. node.parent = camera;
  82597. });
  82598. }
  82599. });
  82600. scene.onAfterCameraRenderObservable.add(function (camera) {
  82601. if (camera.parent === _this && _this.rigParenting) {
  82602. _this._descendants.forEach(function (node) {
  82603. node.parent = _this;
  82604. });
  82605. }
  82606. });
  82607. return _this;
  82608. }
  82609. /**
  82610. * Gets the device distance from the ground in meters.
  82611. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  82612. */
  82613. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  82614. if (this._standingMatrix) {
  82615. // Add standing matrix offset to get real offset from ground in room
  82616. this._standingMatrix.getTranslationToRef(this._workingVector);
  82617. return this._deviceRoomPosition.y + this._workingVector.y;
  82618. }
  82619. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  82620. return this._defaultHeight || 0;
  82621. };
  82622. /**
  82623. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82624. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  82625. */
  82626. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  82627. var _this = this;
  82628. if (callback === void 0) { callback = function (bool) { }; }
  82629. // Use standing matrix if available
  82630. this.getEngine().initWebVRAsync().then(function (result) {
  82631. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  82632. callback(false);
  82633. }
  82634. else {
  82635. _this._standingMatrix = new BABYLON.Matrix();
  82636. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  82637. if (!_this.getScene().useRightHandedSystem) {
  82638. [2, 6, 8, 9, 14].forEach(function (num) {
  82639. if (_this._standingMatrix) {
  82640. _this._standingMatrix.m[num] *= -1;
  82641. }
  82642. });
  82643. }
  82644. callback(true);
  82645. }
  82646. });
  82647. };
  82648. /**
  82649. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82650. * @returns A promise with a boolean set to if the standing matrix is supported.
  82651. */
  82652. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  82653. var _this = this;
  82654. return new Promise(function (res, rej) {
  82655. _this.useStandingMatrix(function (supported) {
  82656. res(supported);
  82657. });
  82658. });
  82659. };
  82660. /**
  82661. * Disposes the camera
  82662. */
  82663. WebVRFreeCamera.prototype.dispose = function () {
  82664. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  82665. _super.prototype.dispose.call(this);
  82666. };
  82667. /**
  82668. * Gets a vrController by name.
  82669. * @param name The name of the controller to retreive
  82670. * @returns the controller matching the name specified or null if not found
  82671. */
  82672. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  82673. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  82674. var gp = _a[_i];
  82675. if (gp.hand === name) {
  82676. return gp;
  82677. }
  82678. }
  82679. return null;
  82680. };
  82681. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  82682. /**
  82683. * The controller corrisponding to the users left hand.
  82684. */
  82685. get: function () {
  82686. if (!this._leftController) {
  82687. this._leftController = this.getControllerByName("left");
  82688. }
  82689. return this._leftController;
  82690. },
  82691. enumerable: true,
  82692. configurable: true
  82693. });
  82694. ;
  82695. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  82696. /**
  82697. * The controller corrisponding to the users right hand.
  82698. */
  82699. get: function () {
  82700. if (!this._rightController) {
  82701. this._rightController = this.getControllerByName("right");
  82702. }
  82703. return this._rightController;
  82704. },
  82705. enumerable: true,
  82706. configurable: true
  82707. });
  82708. ;
  82709. /**
  82710. * Casts a ray forward from the vrCamera's gaze.
  82711. * @param length Length of the ray (default: 100)
  82712. * @returns the ray corrisponding to the gaze
  82713. */
  82714. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  82715. if (length === void 0) { length = 100; }
  82716. if (this.leftCamera) {
  82717. // Use left eye to avoid computation to compute center on every call
  82718. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  82719. }
  82720. else {
  82721. return _super.prototype.getForwardRay.call(this, length);
  82722. }
  82723. };
  82724. /**
  82725. * Updates the camera based on device's frame data
  82726. */
  82727. WebVRFreeCamera.prototype._checkInputs = function () {
  82728. if (this._vrDevice && this._vrDevice.isPresenting) {
  82729. this._vrDevice.getFrameData(this._frameData);
  82730. this.updateFromDevice(this._frameData.pose);
  82731. }
  82732. _super.prototype._checkInputs.call(this);
  82733. };
  82734. /**
  82735. * Updates the poseControlled values based on the input device pose.
  82736. * @param poseData Pose coming from the device
  82737. */
  82738. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82739. if (poseData && poseData.orientation) {
  82740. this.rawPose = poseData;
  82741. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82742. if (this.getScene().useRightHandedSystem) {
  82743. this._deviceRoomRotationQuaternion.z *= -1;
  82744. this._deviceRoomRotationQuaternion.w *= -1;
  82745. }
  82746. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82747. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82748. if (this.getScene().useRightHandedSystem) {
  82749. this._deviceRoomPosition.z *= -1;
  82750. }
  82751. }
  82752. }
  82753. };
  82754. /**
  82755. * WebVR's attach control will start broadcasting frames to the device.
  82756. * Note that in certain browsers (chrome for example) this function must be called
  82757. * within a user-interaction callback. Example:
  82758. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82759. *
  82760. * @param element html element to attach the vrDevice to
  82761. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82762. */
  82763. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82764. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82765. this._attached = true;
  82766. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82767. if (this._vrDevice) {
  82768. this.getEngine().enableVR();
  82769. }
  82770. };
  82771. /**
  82772. * Detaches the camera from the html element and disables VR
  82773. *
  82774. * @param element html element to detach from
  82775. */
  82776. WebVRFreeCamera.prototype.detachControl = function (element) {
  82777. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82778. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82779. _super.prototype.detachControl.call(this, element);
  82780. this._attached = false;
  82781. this.getEngine().disableVR();
  82782. };
  82783. /**
  82784. * @returns the name of this class
  82785. */
  82786. WebVRFreeCamera.prototype.getClassName = function () {
  82787. return "WebVRFreeCamera";
  82788. };
  82789. /**
  82790. * Calls resetPose on the vrDisplay
  82791. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82792. */
  82793. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82794. //uses the vrDisplay's "resetPose()".
  82795. //pitch and roll won't be affected.
  82796. this._vrDevice.resetPose();
  82797. };
  82798. /**
  82799. * Updates the rig cameras (left and right eye)
  82800. */
  82801. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82802. var camLeft = this._rigCameras[0];
  82803. var camRight = this._rigCameras[1];
  82804. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82805. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82806. camLeft.position.copyFrom(this._deviceRoomPosition);
  82807. camRight.position.copyFrom(this._deviceRoomPosition);
  82808. };
  82809. /**
  82810. * Updates the cached values of the camera
  82811. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82812. */
  82813. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82814. var _this = this;
  82815. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82816. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82817. if (!this.updateCacheCalled) {
  82818. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82819. this.updateCacheCalled = true;
  82820. this.update();
  82821. }
  82822. // Set working vector to the device position in room space rotated by the new rotation
  82823. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82824. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82825. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82826. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82827. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82828. // Add translation from anchor position
  82829. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82830. this._workingVector.addInPlace(this.position);
  82831. this._workingVector.subtractInPlace(this._cache.position);
  82832. this._deviceToWorld.setTranslation(this._workingVector);
  82833. // Set an inverted matrix to be used when updating the camera
  82834. this._deviceToWorld.invertToRef(this._worldToDevice);
  82835. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82836. this.controllers.forEach(function (controller) {
  82837. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82838. controller.update();
  82839. });
  82840. }
  82841. if (!ignoreParentClass) {
  82842. _super.prototype._updateCache.call(this);
  82843. }
  82844. this.updateCacheCalled = false;
  82845. };
  82846. /**
  82847. * Updates the current device position and rotation in the babylon world
  82848. */
  82849. WebVRFreeCamera.prototype.update = function () {
  82850. // Get current device position in babylon world
  82851. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82852. // Get current device rotation in babylon world
  82853. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82854. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82855. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82856. _super.prototype.update.call(this);
  82857. };
  82858. /**
  82859. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82860. * @returns an identity matrix
  82861. */
  82862. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82863. return BABYLON.Matrix.Identity();
  82864. };
  82865. /**
  82866. * This function is called by the two RIG cameras.
  82867. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82868. */
  82869. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82870. var _this = this;
  82871. // Update the parent camera prior to using a child camera to avoid desynchronization
  82872. var parentCamera = this._cameraRigParams["parentCamera"];
  82873. parentCamera._updateCache();
  82874. //WebVR 1.1
  82875. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82876. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82877. if (!this.getScene().useRightHandedSystem) {
  82878. [2, 6, 8, 9, 14].forEach(function (num) {
  82879. _this._webvrViewMatrix.m[num] *= -1;
  82880. });
  82881. }
  82882. // update the camera rotation matrix
  82883. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82884. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82885. // Computing target and final matrix
  82886. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82887. // should the view matrix be updated with scale and position offset?
  82888. if (parentCamera.deviceScaleFactor !== 1) {
  82889. this._webvrViewMatrix.invert();
  82890. // scale the position, if set
  82891. if (parentCamera.deviceScaleFactor) {
  82892. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82893. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82894. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82895. }
  82896. this._webvrViewMatrix.invert();
  82897. }
  82898. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82899. return this._webvrViewMatrix;
  82900. };
  82901. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82902. var _this = this;
  82903. var parentCamera = this.parent;
  82904. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82905. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82906. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82907. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82908. //babylon compatible matrix
  82909. if (!this.getScene().useRightHandedSystem) {
  82910. [8, 9, 10, 11].forEach(function (num) {
  82911. _this._projectionMatrix.m[num] *= -1;
  82912. });
  82913. }
  82914. return this._projectionMatrix;
  82915. };
  82916. /**
  82917. * Initializes the controllers and their meshes
  82918. */
  82919. WebVRFreeCamera.prototype.initControllers = function () {
  82920. var _this = this;
  82921. this.controllers = [];
  82922. var manager = this.getScene().gamepadManager;
  82923. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82924. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82925. var webVrController = gamepad;
  82926. if (webVrController.defaultModel) {
  82927. webVrController.defaultModel.setEnabled(false);
  82928. }
  82929. if (webVrController.hand === "right") {
  82930. _this._rightController = null;
  82931. }
  82932. if (webVrController.hand === "left") {
  82933. _this._leftController = null;
  82934. }
  82935. var controllerIndex = _this.controllers.indexOf(webVrController);
  82936. if (controllerIndex !== -1) {
  82937. _this.controllers.splice(controllerIndex, 1);
  82938. }
  82939. }
  82940. });
  82941. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82942. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82943. var webVrController_1 = gamepad;
  82944. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82945. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82946. if (_this.webVROptions.controllerMeshes) {
  82947. if (webVrController_1.defaultModel) {
  82948. webVrController_1.defaultModel.setEnabled(true);
  82949. }
  82950. else {
  82951. // Load the meshes
  82952. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82953. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82954. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82955. if (_this.webVROptions.defaultLightingOnControllers) {
  82956. if (!_this._lightOnControllers) {
  82957. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82958. }
  82959. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82960. var children = mesh.getChildren();
  82961. if (children.length !== 0) {
  82962. children.forEach(function (mesh) {
  82963. light.includedOnlyMeshes.push(mesh);
  82964. activateLightOnSubMeshes_1(mesh, light);
  82965. });
  82966. }
  82967. };
  82968. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82969. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82970. }
  82971. });
  82972. }
  82973. }
  82974. webVrController_1.attachToPoseControlledCamera(_this);
  82975. // since this is async - sanity check. Is the controller already stored?
  82976. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82977. //add to the controllers array
  82978. _this.controllers.push(webVrController_1);
  82979. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82980. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82981. // So we're overriding setting left & right manually to be sure
  82982. var firstViveWandDetected = false;
  82983. for (var i = 0; i < _this.controllers.length; i++) {
  82984. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82985. if (!firstViveWandDetected) {
  82986. firstViveWandDetected = true;
  82987. _this.controllers[i].hand = "left";
  82988. }
  82989. else {
  82990. _this.controllers[i].hand = "right";
  82991. }
  82992. }
  82993. }
  82994. //did we find enough controllers? Great! let the developer know.
  82995. if (_this.controllers.length >= 2) {
  82996. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82997. }
  82998. }
  82999. }
  83000. });
  83001. };
  83002. return WebVRFreeCamera;
  83003. }(BABYLON.FreeCamera));
  83004. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  83005. })(BABYLON || (BABYLON = {}));
  83006. //# sourceMappingURL=babylon.webVRCamera.js.map
  83007. "use strict";
  83008. var BABYLON;
  83009. (function (BABYLON) {
  83010. // We're mainly based on the logic defined into the FreeCamera code
  83011. /**
  83012. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  83013. * being tilted forward or back and left or right.
  83014. */
  83015. var DeviceOrientationCamera = /** @class */ (function (_super) {
  83016. __extends(DeviceOrientationCamera, _super);
  83017. /**
  83018. * Creates a new device orientation camera
  83019. * @param name The name of the camera
  83020. * @param position The start position camera
  83021. * @param scene The scene the camera belongs to
  83022. */
  83023. function DeviceOrientationCamera(name, position, scene) {
  83024. var _this = _super.call(this, name, position, scene) || this;
  83025. _this._quaternionCache = new BABYLON.Quaternion();
  83026. _this.inputs.addDeviceOrientation();
  83027. return _this;
  83028. }
  83029. /**
  83030. * Gets the current instance class name ("DeviceOrientationCamera").
  83031. * This helps avoiding instanceof at run time.
  83032. * @returns the class name
  83033. */
  83034. DeviceOrientationCamera.prototype.getClassName = function () {
  83035. return "DeviceOrientationCamera";
  83036. };
  83037. /**
  83038. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  83039. */
  83040. DeviceOrientationCamera.prototype._checkInputs = function () {
  83041. _super.prototype._checkInputs.call(this);
  83042. this._quaternionCache.copyFrom(this.rotationQuaternion);
  83043. if (this._initialQuaternion) {
  83044. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  83045. }
  83046. };
  83047. /**
  83048. * Reset the camera to its default orientation on the specified axis only.
  83049. * @param axis The axis to reset
  83050. */
  83051. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  83052. var _this = this;
  83053. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  83054. //can only work if this camera has a rotation quaternion already.
  83055. if (!this.rotationQuaternion)
  83056. return;
  83057. if (!this._initialQuaternion) {
  83058. this._initialQuaternion = new BABYLON.Quaternion();
  83059. }
  83060. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  83061. ['x', 'y', 'z'].forEach(function (axisName) {
  83062. if (!axis[axisName]) {
  83063. _this._initialQuaternion[axisName] = 0;
  83064. }
  83065. else {
  83066. _this._initialQuaternion[axisName] *= -1;
  83067. }
  83068. });
  83069. this._initialQuaternion.normalize();
  83070. //force rotation update
  83071. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  83072. };
  83073. return DeviceOrientationCamera;
  83074. }(BABYLON.FreeCamera));
  83075. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  83076. })(BABYLON || (BABYLON = {}));
  83077. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  83078. "use strict";
  83079. var BABYLON;
  83080. (function (BABYLON) {
  83081. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  83082. __extends(VRDeviceOrientationFreeCamera, _super);
  83083. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  83084. if (compensateDistortion === void 0) { compensateDistortion = true; }
  83085. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  83086. var _this = _super.call(this, name, position, scene) || this;
  83087. vrCameraMetrics.compensateDistortion = compensateDistortion;
  83088. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  83089. return _this;
  83090. }
  83091. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  83092. return "VRDeviceOrientationFreeCamera";
  83093. };
  83094. return VRDeviceOrientationFreeCamera;
  83095. }(BABYLON.DeviceOrientationCamera));
  83096. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  83097. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  83098. __extends(VRDeviceOrientationGamepadCamera, _super);
  83099. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  83100. if (compensateDistortion === void 0) { compensateDistortion = true; }
  83101. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  83102. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  83103. _this.inputs.addGamepad();
  83104. return _this;
  83105. }
  83106. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  83107. return "VRDeviceOrientationGamepadCamera";
  83108. };
  83109. return VRDeviceOrientationGamepadCamera;
  83110. }(VRDeviceOrientationFreeCamera));
  83111. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  83112. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  83113. __extends(VRDeviceOrientationArcRotateCamera, _super);
  83114. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  83115. if (compensateDistortion === void 0) { compensateDistortion = true; }
  83116. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  83117. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  83118. vrCameraMetrics.compensateDistortion = compensateDistortion;
  83119. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  83120. _this.inputs.addVRDeviceOrientation();
  83121. return _this;
  83122. }
  83123. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  83124. return "VRDeviceOrientationArcRotateCamera";
  83125. };
  83126. return VRDeviceOrientationArcRotateCamera;
  83127. }(BABYLON.ArcRotateCamera));
  83128. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  83129. })(BABYLON || (BABYLON = {}));
  83130. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  83131. "use strict";
  83132. var BABYLON;
  83133. (function (BABYLON) {
  83134. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  83135. __extends(AnaglyphFreeCamera, _super);
  83136. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  83137. var _this = _super.call(this, name, position, scene) || this;
  83138. _this.interaxialDistance = interaxialDistance;
  83139. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  83140. return _this;
  83141. }
  83142. AnaglyphFreeCamera.prototype.getClassName = function () {
  83143. return "AnaglyphFreeCamera";
  83144. };
  83145. return AnaglyphFreeCamera;
  83146. }(BABYLON.FreeCamera));
  83147. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  83148. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  83149. __extends(AnaglyphArcRotateCamera, _super);
  83150. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  83151. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  83152. _this.interaxialDistance = interaxialDistance;
  83153. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  83154. return _this;
  83155. }
  83156. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  83157. return "AnaglyphArcRotateCamera";
  83158. };
  83159. return AnaglyphArcRotateCamera;
  83160. }(BABYLON.ArcRotateCamera));
  83161. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  83162. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  83163. __extends(AnaglyphGamepadCamera, _super);
  83164. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  83165. var _this = _super.call(this, name, position, scene) || this;
  83166. _this.interaxialDistance = interaxialDistance;
  83167. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  83168. return _this;
  83169. }
  83170. AnaglyphGamepadCamera.prototype.getClassName = function () {
  83171. return "AnaglyphGamepadCamera";
  83172. };
  83173. return AnaglyphGamepadCamera;
  83174. }(BABYLON.GamepadCamera));
  83175. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  83176. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  83177. __extends(AnaglyphUniversalCamera, _super);
  83178. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  83179. var _this = _super.call(this, name, position, scene) || this;
  83180. _this.interaxialDistance = interaxialDistance;
  83181. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  83182. return _this;
  83183. }
  83184. AnaglyphUniversalCamera.prototype.getClassName = function () {
  83185. return "AnaglyphUniversalCamera";
  83186. };
  83187. return AnaglyphUniversalCamera;
  83188. }(BABYLON.UniversalCamera));
  83189. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  83190. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  83191. __extends(StereoscopicFreeCamera, _super);
  83192. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  83193. var _this = _super.call(this, name, position, scene) || this;
  83194. _this.interaxialDistance = interaxialDistance;
  83195. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  83196. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  83197. return _this;
  83198. }
  83199. StereoscopicFreeCamera.prototype.getClassName = function () {
  83200. return "StereoscopicFreeCamera";
  83201. };
  83202. return StereoscopicFreeCamera;
  83203. }(BABYLON.FreeCamera));
  83204. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  83205. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  83206. __extends(StereoscopicArcRotateCamera, _super);
  83207. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  83208. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  83209. _this.interaxialDistance = interaxialDistance;
  83210. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  83211. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  83212. return _this;
  83213. }
  83214. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  83215. return "StereoscopicArcRotateCamera";
  83216. };
  83217. return StereoscopicArcRotateCamera;
  83218. }(BABYLON.ArcRotateCamera));
  83219. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  83220. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  83221. __extends(StereoscopicGamepadCamera, _super);
  83222. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  83223. var _this = _super.call(this, name, position, scene) || this;
  83224. _this.interaxialDistance = interaxialDistance;
  83225. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  83226. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  83227. return _this;
  83228. }
  83229. StereoscopicGamepadCamera.prototype.getClassName = function () {
  83230. return "StereoscopicGamepadCamera";
  83231. };
  83232. return StereoscopicGamepadCamera;
  83233. }(BABYLON.GamepadCamera));
  83234. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  83235. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  83236. __extends(StereoscopicUniversalCamera, _super);
  83237. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  83238. var _this = _super.call(this, name, position, scene) || this;
  83239. _this.interaxialDistance = interaxialDistance;
  83240. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  83241. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  83242. return _this;
  83243. }
  83244. StereoscopicUniversalCamera.prototype.getClassName = function () {
  83245. return "StereoscopicUniversalCamera";
  83246. };
  83247. return StereoscopicUniversalCamera;
  83248. }(BABYLON.UniversalCamera));
  83249. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  83250. })(BABYLON || (BABYLON = {}));
  83251. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  83252. "use strict";
  83253. var BABYLON;
  83254. (function (BABYLON) {
  83255. var VRExperienceHelperGazer = /** @class */ (function () {
  83256. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  83257. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  83258. this.scene = scene;
  83259. this._pointerDownOnMeshAsked = false;
  83260. this._isActionableMesh = false;
  83261. this._teleportationRequestInitiated = false;
  83262. this._teleportationBackRequestInitiated = false;
  83263. this._dpadPressed = true;
  83264. this._activePointer = false;
  83265. this._id = VRExperienceHelperGazer._idCounter++;
  83266. // Gaze tracker
  83267. if (!gazeTrackerToClone) {
  83268. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  83269. this._gazeTracker.bakeCurrentTransformIntoVertices();
  83270. this._gazeTracker.isPickable = false;
  83271. this._gazeTracker.isVisible = false;
  83272. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  83273. targetMat.specularColor = BABYLON.Color3.Black();
  83274. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  83275. targetMat.backFaceCulling = false;
  83276. this._gazeTracker.material = targetMat;
  83277. }
  83278. else {
  83279. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  83280. }
  83281. }
  83282. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  83283. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  83284. };
  83285. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  83286. this._pointerDownOnMeshAsked = true;
  83287. if (this._currentMeshSelected && this._currentHit) {
  83288. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  83289. }
  83290. };
  83291. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  83292. if (this._currentMeshSelected && this._currentHit) {
  83293. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  83294. }
  83295. this._pointerDownOnMeshAsked = false;
  83296. };
  83297. VRExperienceHelperGazer.prototype._activatePointer = function () {
  83298. this._activePointer = true;
  83299. };
  83300. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  83301. this._activePointer = false;
  83302. };
  83303. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  83304. };
  83305. VRExperienceHelperGazer.prototype.dispose = function () {
  83306. this._interactionsEnabled = false;
  83307. this._teleportationEnabled = false;
  83308. };
  83309. VRExperienceHelperGazer._idCounter = 0;
  83310. return VRExperienceHelperGazer;
  83311. }());
  83312. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  83313. __extends(VRExperienceHelperControllerGazer, _super);
  83314. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  83315. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  83316. _this.webVRController = webVRController;
  83317. // Laser pointer
  83318. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  83319. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  83320. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  83321. laserPointerMaterial.alpha = 0.6;
  83322. _this._laserPointer.material = laserPointerMaterial;
  83323. _this._laserPointer.rotation.x = Math.PI / 2;
  83324. _this._laserPointer.position.z = -0.5;
  83325. _this._laserPointer.isVisible = false;
  83326. if (!webVRController.mesh) {
  83327. // Create an empty mesh that is used prior to loading the high quality model
  83328. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  83329. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  83330. preloadPointerPose.rotation.x = -0.7;
  83331. preloadMesh.addChild(preloadPointerPose);
  83332. webVRController.attachToMesh(preloadMesh);
  83333. }
  83334. _this._setLaserPointerParent(webVRController.mesh);
  83335. return _this;
  83336. }
  83337. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  83338. return this.webVRController.getForwardRay(length);
  83339. };
  83340. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  83341. _super.prototype._activatePointer.call(this);
  83342. this._laserPointer.isVisible = true;
  83343. };
  83344. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  83345. _super.prototype._deactivatePointer.call(this);
  83346. this._laserPointer.isVisible = false;
  83347. };
  83348. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  83349. this._laserPointer.material.emissiveColor = color;
  83350. };
  83351. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  83352. var makeNotPick = function (root) {
  83353. root.name += " laserPointer";
  83354. root.getChildMeshes().forEach(function (c) {
  83355. makeNotPick(c);
  83356. });
  83357. };
  83358. makeNotPick(mesh);
  83359. var childMeshes = mesh.getChildMeshes();
  83360. this.webVRController._pointingPoseNode = null;
  83361. for (var i = 0; i < childMeshes.length; i++) {
  83362. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  83363. mesh = childMeshes[i];
  83364. this.webVRController._pointingPoseNode = mesh;
  83365. break;
  83366. }
  83367. }
  83368. this._laserPointer.parent = mesh;
  83369. };
  83370. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  83371. this._laserPointer.scaling.y = distance;
  83372. this._laserPointer.position.z = -distance / 2;
  83373. };
  83374. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  83375. _super.prototype.dispose.call(this);
  83376. this._laserPointer.dispose();
  83377. };
  83378. return VRExperienceHelperControllerGazer;
  83379. }(VRExperienceHelperGazer));
  83380. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  83381. __extends(VRExperienceHelperCameraGazer, _super);
  83382. function VRExperienceHelperCameraGazer(getCamera, scene) {
  83383. var _this = _super.call(this, scene) || this;
  83384. _this.getCamera = getCamera;
  83385. return _this;
  83386. }
  83387. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  83388. var camera = this.getCamera();
  83389. if (camera) {
  83390. return camera.getForwardRay(length);
  83391. }
  83392. else {
  83393. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  83394. }
  83395. };
  83396. return VRExperienceHelperCameraGazer;
  83397. }(VRExperienceHelperGazer));
  83398. /**
  83399. * Helps to quickly add VR support to an existing scene.
  83400. * See http://doc.babylonjs.com/how_to/webvr_helper
  83401. */
  83402. var VRExperienceHelper = /** @class */ (function () {
  83403. /**
  83404. * Instantiates a VRExperienceHelper.
  83405. * Helps to quickly add VR support to an existing scene.
  83406. * @param scene The scene the VRExperienceHelper belongs to.
  83407. * @param webVROptions Options to modify the vr experience helper's behavior.
  83408. */
  83409. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  83410. if (webVROptions === void 0) { webVROptions = {}; }
  83411. var _this = this;
  83412. this.webVROptions = webVROptions;
  83413. // Can the system support WebVR, even if a headset isn't plugged in?
  83414. this._webVRsupported = false;
  83415. // If WebVR is supported, is a headset plugged in and are we ready to present?
  83416. this._webVRready = false;
  83417. // Are we waiting for the requestPresent callback to complete?
  83418. this._webVRrequesting = false;
  83419. // Are we presenting to the headset right now?
  83420. this._webVRpresenting = false;
  83421. // Are we presenting in the fullscreen fallback?
  83422. this._fullscreenVRpresenting = false;
  83423. /**
  83424. * Observable raised when entering VR.
  83425. */
  83426. this.onEnteringVRObservable = new BABYLON.Observable();
  83427. /**
  83428. * Observable raised when exiting VR.
  83429. */
  83430. this.onExitingVRObservable = new BABYLON.Observable();
  83431. /**
  83432. * Observable raised when controller mesh is loaded.
  83433. */
  83434. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  83435. this._useCustomVRButton = false;
  83436. this._teleportationRequested = false;
  83437. this._teleportActive = false;
  83438. this._floorMeshesCollection = [];
  83439. this._rotationAllowed = true;
  83440. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  83441. this._rotationRightAsked = false;
  83442. this._rotationLeftAsked = false;
  83443. this._isDefaultTeleportationTarget = true;
  83444. this._teleportationFillColor = "#444444";
  83445. this._teleportationBorderColor = "#FFFFFF";
  83446. this._rotationAngle = 0;
  83447. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  83448. this._padSensibilityUp = 0.65;
  83449. this._padSensibilityDown = 0.35;
  83450. this.leftController = null;
  83451. this.rightController = null;
  83452. /**
  83453. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  83454. */
  83455. this.onNewMeshSelected = new BABYLON.Observable();
  83456. /**
  83457. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  83458. */
  83459. this.onNewMeshPicked = new BABYLON.Observable();
  83460. /**
  83461. * Observable raised before camera teleportation
  83462. */
  83463. this.onBeforeCameraTeleport = new BABYLON.Observable();
  83464. /**
  83465. * Observable raised after camera teleportation
  83466. */
  83467. this.onAfterCameraTeleport = new BABYLON.Observable();
  83468. /**
  83469. * Observable raised when current selected mesh gets unselected
  83470. */
  83471. this.onSelectedMeshUnselected = new BABYLON.Observable();
  83472. /**
  83473. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  83474. */
  83475. this.teleportationEnabled = true;
  83476. this._teleportationInitialized = false;
  83477. this._interactionsEnabled = false;
  83478. this._interactionsRequested = false;
  83479. this._displayGaze = true;
  83480. this._displayLaserPointer = true;
  83481. this._onResize = function () {
  83482. _this.moveButtonToBottomRight();
  83483. if (_this._fullscreenVRpresenting && _this._webVRready) {
  83484. _this.exitVR();
  83485. }
  83486. };
  83487. this._onFullscreenChange = function () {
  83488. if (document.fullscreen !== undefined) {
  83489. _this._fullscreenVRpresenting = document.fullscreen;
  83490. }
  83491. else if (document.mozFullScreen !== undefined) {
  83492. _this._fullscreenVRpresenting = document.mozFullScreen;
  83493. }
  83494. else if (document.webkitIsFullScreen !== undefined) {
  83495. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  83496. }
  83497. else if (document.msIsFullScreen !== undefined) {
  83498. _this._fullscreenVRpresenting = document.msIsFullScreen;
  83499. }
  83500. if (!_this._fullscreenVRpresenting && _this._canvas) {
  83501. _this.exitVR();
  83502. if (!_this._useCustomVRButton) {
  83503. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  83504. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  83505. }
  83506. }
  83507. };
  83508. this.beforeRender = function () {
  83509. if (_this.leftController && _this.leftController._activePointer) {
  83510. _this._castRayAndSelectObject(_this.leftController);
  83511. }
  83512. if (_this.rightController && _this.rightController._activePointer) {
  83513. _this._castRayAndSelectObject(_this.rightController);
  83514. }
  83515. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  83516. _this._castRayAndSelectObject(_this._cameraGazer);
  83517. }
  83518. else {
  83519. _this._cameraGazer._gazeTracker.isVisible = false;
  83520. }
  83521. };
  83522. this._onNewGamepadConnected = function (gamepad) {
  83523. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  83524. if (gamepad.leftStick) {
  83525. gamepad.onleftstickchanged(function (stickValues) {
  83526. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  83527. // Listening to classic/xbox gamepad only if no VR controller is active
  83528. if ((!_this.leftController && !_this.rightController) ||
  83529. ((_this.leftController && !_this.leftController._activePointer) &&
  83530. (_this.rightController && !_this.rightController._activePointer))) {
  83531. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  83532. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  83533. }
  83534. }
  83535. });
  83536. }
  83537. if (gamepad.rightStick) {
  83538. gamepad.onrightstickchanged(function (stickValues) {
  83539. if (_this._teleportationInitialized) {
  83540. _this._checkRotate(stickValues, _this._cameraGazer);
  83541. }
  83542. });
  83543. }
  83544. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  83545. gamepad.onbuttondown(function (buttonPressed) {
  83546. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83547. _this._cameraGazer._selectionPointerDown();
  83548. }
  83549. });
  83550. gamepad.onbuttonup(function (buttonPressed) {
  83551. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83552. _this._cameraGazer._selectionPointerUp();
  83553. }
  83554. });
  83555. }
  83556. }
  83557. else {
  83558. var webVRController = gamepad;
  83559. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  83560. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  83561. _this.rightController = controller;
  83562. }
  83563. else {
  83564. _this.leftController = controller;
  83565. }
  83566. _this._tryEnableInteractionOnController(controller);
  83567. }
  83568. };
  83569. // 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
  83570. this._tryEnableInteractionOnController = function (controller) {
  83571. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  83572. _this._enableInteractionOnController(controller);
  83573. }
  83574. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  83575. _this._enableTeleportationOnController(controller);
  83576. }
  83577. };
  83578. this._onNewGamepadDisconnected = function (gamepad) {
  83579. if (gamepad instanceof BABYLON.WebVRController) {
  83580. if (gamepad.hand === "left" && _this.leftController != null) {
  83581. _this.leftController.dispose();
  83582. _this.leftController = null;
  83583. }
  83584. if (gamepad.hand === "right" && _this.rightController != null) {
  83585. _this.rightController.dispose();
  83586. _this.rightController = null;
  83587. }
  83588. }
  83589. };
  83590. this._workingVector = BABYLON.Vector3.Zero();
  83591. this._workingQuaternion = BABYLON.Quaternion.Identity();
  83592. this._workingMatrix = BABYLON.Matrix.Identity();
  83593. this._scene = scene;
  83594. this._canvas = scene.getEngine().getRenderingCanvas();
  83595. // Parse options
  83596. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  83597. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  83598. }
  83599. if (webVROptions.createDeviceOrientationCamera === undefined) {
  83600. webVROptions.createDeviceOrientationCamera = true;
  83601. }
  83602. if (webVROptions.defaultHeight === undefined) {
  83603. webVROptions.defaultHeight = 1.7;
  83604. }
  83605. if (webVROptions.useCustomVRButton) {
  83606. this._useCustomVRButton = true;
  83607. if (webVROptions.customVRButton) {
  83608. this._btnVR = webVROptions.customVRButton;
  83609. }
  83610. }
  83611. if (webVROptions.rayLength) {
  83612. this._rayLength = webVROptions.rayLength;
  83613. }
  83614. this._defaultHeight = webVROptions.defaultHeight;
  83615. if (webVROptions.positionScale) {
  83616. this._rayLength *= webVROptions.positionScale;
  83617. this._defaultHeight *= webVROptions.positionScale;
  83618. }
  83619. // Set position
  83620. if (this._scene.activeCamera) {
  83621. this._position = this._scene.activeCamera.position.clone();
  83622. }
  83623. else {
  83624. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  83625. }
  83626. // Set non-vr camera
  83627. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  83628. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  83629. // Copy data from existing camera
  83630. if (this._scene.activeCamera) {
  83631. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  83632. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  83633. // Set rotation from previous camera
  83634. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  83635. var targetCamera = this._scene.activeCamera;
  83636. if (targetCamera.rotationQuaternion) {
  83637. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  83638. }
  83639. else {
  83640. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  83641. }
  83642. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  83643. }
  83644. }
  83645. this._scene.activeCamera = this._deviceOrientationCamera;
  83646. if (this._canvas) {
  83647. this._scene.activeCamera.attachControl(this._canvas);
  83648. }
  83649. }
  83650. else {
  83651. this._existingCamera = this._scene.activeCamera;
  83652. }
  83653. // Create VR cameras
  83654. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83655. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  83656. }
  83657. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  83658. this._webVRCamera.useStandingMatrix();
  83659. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  83660. // Create default button
  83661. if (!this._useCustomVRButton) {
  83662. this._btnVR = document.createElement("BUTTON");
  83663. this._btnVR.className = "babylonVRicon";
  83664. this._btnVR.id = "babylonVRiconbtn";
  83665. this._btnVR.title = "Click to switch to VR";
  83666. 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) }";
  83667. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  83668. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  83669. // css += ".babylonVRicon.vrdisplaysupported { }";
  83670. // css += ".babylonVRicon.vrdisplayready { }";
  83671. // css += ".babylonVRicon.vrdisplayrequesting { }";
  83672. var style = document.createElement('style');
  83673. style.appendChild(document.createTextNode(css));
  83674. document.getElementsByTagName('head')[0].appendChild(style);
  83675. this.moveButtonToBottomRight();
  83676. }
  83677. // VR button click event
  83678. if (this._btnVR) {
  83679. this._btnVR.addEventListener("click", function () {
  83680. if (!_this.isInVRMode) {
  83681. _this.enterVR();
  83682. }
  83683. else {
  83684. _this.exitVR();
  83685. }
  83686. });
  83687. }
  83688. // Window events
  83689. window.addEventListener("resize", this._onResize);
  83690. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  83691. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  83692. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  83693. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  83694. // Display vr button when headset is connected
  83695. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83696. this.displayVRButton();
  83697. }
  83698. else {
  83699. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  83700. if (e.vrDisplay) {
  83701. _this.displayVRButton();
  83702. }
  83703. });
  83704. }
  83705. // Exiting VR mode using 'ESC' key on desktop
  83706. this._onKeyDown = function (event) {
  83707. if (event.keyCode === 27 && _this.isInVRMode) {
  83708. _this.exitVR();
  83709. }
  83710. };
  83711. document.addEventListener("keydown", this._onKeyDown);
  83712. // Exiting VR mode double tapping the touch screen
  83713. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  83714. if (_this.isInVRMode) {
  83715. _this.exitVR();
  83716. if (_this._fullscreenVRpresenting) {
  83717. _this._scene.getEngine().switchFullscreen(true);
  83718. }
  83719. }
  83720. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  83721. // Listen for WebVR display changes
  83722. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  83723. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  83724. this._onVRRequestPresentStart = function () {
  83725. _this._webVRrequesting = true;
  83726. _this.updateButtonVisibility();
  83727. };
  83728. this._onVRRequestPresentComplete = function (success) {
  83729. _this._webVRrequesting = false;
  83730. _this.updateButtonVisibility();
  83731. };
  83732. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83733. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83734. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83735. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83736. scene.onDisposeObservable.add(function () {
  83737. _this.dispose();
  83738. });
  83739. // Gamepad connection events
  83740. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83741. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83742. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83743. this.updateButtonVisibility();
  83744. //create easing functions
  83745. this._circleEase = new BABYLON.CircleEase();
  83746. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83747. }
  83748. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83749. /** Return this.onEnteringVRObservable
  83750. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83751. */
  83752. get: function () {
  83753. return this.onEnteringVRObservable;
  83754. },
  83755. enumerable: true,
  83756. configurable: true
  83757. });
  83758. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83759. /** Return this.onExitingVRObservable
  83760. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83761. */
  83762. get: function () {
  83763. return this.onExitingVRObservable;
  83764. },
  83765. enumerable: true,
  83766. configurable: true
  83767. });
  83768. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83769. /** Return this.onControllerMeshLoadedObservable
  83770. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83771. */
  83772. get: function () {
  83773. return this.onControllerMeshLoadedObservable;
  83774. },
  83775. enumerable: true,
  83776. configurable: true
  83777. });
  83778. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83779. /**
  83780. * The mesh used to display where the user is going to teleport.
  83781. */
  83782. get: function () {
  83783. return this._teleportationTarget;
  83784. },
  83785. /**
  83786. * Sets the mesh to be used to display where the user is going to teleport.
  83787. */
  83788. set: function (value) {
  83789. if (value) {
  83790. value.name = "teleportationTarget";
  83791. this._isDefaultTeleportationTarget = false;
  83792. this._teleportationTarget = value;
  83793. }
  83794. },
  83795. enumerable: true,
  83796. configurable: true
  83797. });
  83798. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83799. /**
  83800. * The mesh used to display where the user is selecting,
  83801. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83802. * See http://doc.babylonjs.com/resources/baking_transformations
  83803. */
  83804. get: function () {
  83805. return this._cameraGazer._gazeTracker;
  83806. },
  83807. set: function (value) {
  83808. if (value) {
  83809. this._cameraGazer._gazeTracker = value;
  83810. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83811. this._cameraGazer._gazeTracker.isPickable = false;
  83812. this._cameraGazer._gazeTracker.isVisible = false;
  83813. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83814. if (this.leftController) {
  83815. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83816. }
  83817. if (this.rightController) {
  83818. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83819. }
  83820. }
  83821. },
  83822. enumerable: true,
  83823. configurable: true
  83824. });
  83825. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83826. /**
  83827. * If the ray of the gaze should be displayed.
  83828. */
  83829. get: function () {
  83830. return this._displayGaze;
  83831. },
  83832. /**
  83833. * Sets if the ray of the gaze should be displayed.
  83834. */
  83835. set: function (value) {
  83836. this._displayGaze = value;
  83837. if (!value) {
  83838. this._cameraGazer._gazeTracker.isVisible = false;
  83839. if (this.leftController) {
  83840. this.leftController._gazeTracker.isVisible = false;
  83841. }
  83842. if (this.rightController) {
  83843. this.rightController._gazeTracker.isVisible = false;
  83844. }
  83845. }
  83846. },
  83847. enumerable: true,
  83848. configurable: true
  83849. });
  83850. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83851. /**
  83852. * If the ray of the LaserPointer should be displayed.
  83853. */
  83854. get: function () {
  83855. return this._displayLaserPointer;
  83856. },
  83857. /**
  83858. * Sets if the ray of the LaserPointer should be displayed.
  83859. */
  83860. set: function (value) {
  83861. this._displayLaserPointer = value;
  83862. if (!value) {
  83863. if (this.rightController) {
  83864. this.rightController._deactivatePointer();
  83865. this.rightController._gazeTracker.isVisible = false;
  83866. }
  83867. if (this.leftController) {
  83868. this.leftController._deactivatePointer();
  83869. this.leftController._gazeTracker.isVisible = false;
  83870. }
  83871. }
  83872. else {
  83873. if (this.rightController) {
  83874. this.rightController._activatePointer();
  83875. }
  83876. else if (this.leftController) {
  83877. this.leftController._activatePointer();
  83878. }
  83879. }
  83880. },
  83881. enumerable: true,
  83882. configurable: true
  83883. });
  83884. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83885. /**
  83886. * The deviceOrientationCamera used as the camera when not in VR.
  83887. */
  83888. get: function () {
  83889. return this._deviceOrientationCamera;
  83890. },
  83891. enumerable: true,
  83892. configurable: true
  83893. });
  83894. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83895. /**
  83896. * Based on the current WebVR support, returns the current VR camera used.
  83897. */
  83898. get: function () {
  83899. if (this._webVRready) {
  83900. return this._webVRCamera;
  83901. }
  83902. else {
  83903. return this._scene.activeCamera;
  83904. }
  83905. },
  83906. enumerable: true,
  83907. configurable: true
  83908. });
  83909. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83910. /**
  83911. * The webVRCamera which is used when in VR.
  83912. */
  83913. get: function () {
  83914. return this._webVRCamera;
  83915. },
  83916. enumerable: true,
  83917. configurable: true
  83918. });
  83919. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83920. /**
  83921. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83922. */
  83923. get: function () {
  83924. return this._vrDeviceOrientationCamera;
  83925. },
  83926. enumerable: true,
  83927. configurable: true
  83928. });
  83929. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83930. get: function () {
  83931. var result = this._cameraGazer._teleportationRequestInitiated
  83932. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83933. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83934. return result;
  83935. },
  83936. enumerable: true,
  83937. configurable: true
  83938. });
  83939. // Raised when one of the controller has loaded successfully its associated default mesh
  83940. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83941. if (this.leftController && this.leftController.webVRController == webVRController) {
  83942. if (webVRController.mesh) {
  83943. this.leftController._setLaserPointerParent(webVRController.mesh);
  83944. }
  83945. }
  83946. if (this.rightController && this.rightController.webVRController == webVRController) {
  83947. if (webVRController.mesh) {
  83948. this.rightController._setLaserPointerParent(webVRController.mesh);
  83949. }
  83950. }
  83951. try {
  83952. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83953. }
  83954. catch (err) {
  83955. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83956. }
  83957. };
  83958. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83959. /**
  83960. * Gets a value indicating if we are currently in VR mode.
  83961. */
  83962. get: function () {
  83963. return this._webVRpresenting || this._fullscreenVRpresenting;
  83964. },
  83965. enumerable: true,
  83966. configurable: true
  83967. });
  83968. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83969. var vrDisplay = this._scene.getEngine().getVRDevice();
  83970. if (vrDisplay) {
  83971. var wasPresenting = this._webVRpresenting;
  83972. // A VR display is connected
  83973. this._webVRpresenting = vrDisplay.isPresenting;
  83974. if (wasPresenting && !this._webVRpresenting)
  83975. this.exitVR();
  83976. }
  83977. else {
  83978. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83979. }
  83980. this.updateButtonVisibility();
  83981. };
  83982. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83983. this._webVRsupported = eventArgs.vrSupported;
  83984. this._webVRready = !!eventArgs.vrDisplay;
  83985. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83986. this.updateButtonVisibility();
  83987. };
  83988. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83989. if (this._canvas && !this._useCustomVRButton) {
  83990. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83991. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83992. }
  83993. };
  83994. VRExperienceHelper.prototype.displayVRButton = function () {
  83995. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83996. document.body.appendChild(this._btnVR);
  83997. this._btnVRDisplayed = true;
  83998. }
  83999. };
  84000. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  84001. if (!this._btnVR || this._useCustomVRButton) {
  84002. return;
  84003. }
  84004. this._btnVR.className = "babylonVRicon";
  84005. if (this.isInVRMode) {
  84006. this._btnVR.className += " vrdisplaypresenting";
  84007. }
  84008. else {
  84009. if (this._webVRready)
  84010. this._btnVR.className += " vrdisplayready";
  84011. if (this._webVRsupported)
  84012. this._btnVR.className += " vrdisplaysupported";
  84013. if (this._webVRrequesting)
  84014. this._btnVR.className += " vrdisplayrequesting";
  84015. }
  84016. };
  84017. /**
  84018. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  84019. * Otherwise, will use the fullscreen API.
  84020. */
  84021. VRExperienceHelper.prototype.enterVR = function () {
  84022. if (this.onEnteringVRObservable) {
  84023. try {
  84024. this.onEnteringVRObservable.notifyObservers(this);
  84025. }
  84026. catch (err) {
  84027. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  84028. }
  84029. }
  84030. if (this._scene.activeCamera) {
  84031. this._position = this._scene.activeCamera.position.clone();
  84032. // make sure that we return to the last active camera
  84033. this._existingCamera = this._scene.activeCamera;
  84034. }
  84035. if (this._webVRrequesting)
  84036. return;
  84037. // If WebVR is supported and a headset is connected
  84038. if (this._webVRready) {
  84039. if (!this._webVRpresenting) {
  84040. this._webVRCamera.position = this._position;
  84041. this._scene.activeCamera = this._webVRCamera;
  84042. }
  84043. }
  84044. else if (this._vrDeviceOrientationCamera) {
  84045. this._vrDeviceOrientationCamera.position = this._position;
  84046. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  84047. this._scene.getEngine().switchFullscreen(true);
  84048. this.updateButtonVisibility();
  84049. }
  84050. if (this._scene.activeCamera && this._canvas) {
  84051. this._scene.activeCamera.attachControl(this._canvas);
  84052. }
  84053. if (this._interactionsEnabled) {
  84054. this._scene.registerBeforeRender(this.beforeRender);
  84055. }
  84056. };
  84057. /**
  84058. * Attempt to exit VR, or fullscreen.
  84059. */
  84060. VRExperienceHelper.prototype.exitVR = function () {
  84061. if (this.onExitingVRObservable) {
  84062. try {
  84063. this.onExitingVRObservable.notifyObservers(this);
  84064. }
  84065. catch (err) {
  84066. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  84067. }
  84068. }
  84069. if (this._webVRpresenting) {
  84070. this._scene.getEngine().disableVR();
  84071. }
  84072. if (this._scene.activeCamera) {
  84073. this._position = this._scene.activeCamera.position.clone();
  84074. }
  84075. if (this._deviceOrientationCamera) {
  84076. this._deviceOrientationCamera.position = this._position;
  84077. this._scene.activeCamera = this._deviceOrientationCamera;
  84078. if (this._canvas) {
  84079. this._scene.activeCamera.attachControl(this._canvas);
  84080. }
  84081. }
  84082. else if (this._existingCamera) {
  84083. this._existingCamera.position = this._position;
  84084. this._scene.activeCamera = this._existingCamera;
  84085. }
  84086. this.updateButtonVisibility();
  84087. if (this._interactionsEnabled) {
  84088. this._scene.unregisterBeforeRender(this.beforeRender);
  84089. }
  84090. };
  84091. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  84092. /**
  84093. * The position of the vr experience helper.
  84094. */
  84095. get: function () {
  84096. return this._position;
  84097. },
  84098. /**
  84099. * Sets the position of the vr experience helper.
  84100. */
  84101. set: function (value) {
  84102. this._position = value;
  84103. if (this._scene.activeCamera) {
  84104. this._scene.activeCamera.position = value;
  84105. }
  84106. },
  84107. enumerable: true,
  84108. configurable: true
  84109. });
  84110. /**
  84111. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  84112. */
  84113. VRExperienceHelper.prototype.enableInteractions = function () {
  84114. var _this = this;
  84115. if (!this._interactionsEnabled) {
  84116. this._interactionsRequested = true;
  84117. if (this.leftController) {
  84118. this._enableInteractionOnController(this.leftController);
  84119. }
  84120. if (this.rightController) {
  84121. this._enableInteractionOnController(this.rightController);
  84122. }
  84123. this.raySelectionPredicate = function (mesh) {
  84124. return mesh.isVisible;
  84125. };
  84126. this.meshSelectionPredicate = function (mesh) {
  84127. return true;
  84128. };
  84129. this._raySelectionPredicate = function (mesh) {
  84130. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  84131. && mesh.name.indexOf("teleportationTarget") === -1
  84132. && mesh.name.indexOf("torusTeleportation") === -1
  84133. && mesh.name.indexOf("laserPointer") === -1)) {
  84134. return _this.raySelectionPredicate(mesh);
  84135. }
  84136. return false;
  84137. };
  84138. this._interactionsEnabled = true;
  84139. }
  84140. };
  84141. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  84142. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  84143. if (this._floorMeshesCollection[i].id === mesh.id) {
  84144. return true;
  84145. }
  84146. }
  84147. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  84148. return true;
  84149. }
  84150. return false;
  84151. };
  84152. /**
  84153. * Adds a floor mesh to be used for teleportation.
  84154. * @param floorMesh the mesh to be used for teleportation.
  84155. */
  84156. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  84157. if (!this._floorMeshesCollection) {
  84158. return;
  84159. }
  84160. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  84161. return;
  84162. }
  84163. this._floorMeshesCollection.push(floorMesh);
  84164. };
  84165. /**
  84166. * Removes a floor mesh from being used for teleportation.
  84167. * @param floorMesh the mesh to be removed.
  84168. */
  84169. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  84170. if (!this._floorMeshesCollection) {
  84171. return;
  84172. }
  84173. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  84174. if (meshIndex !== -1) {
  84175. this._floorMeshesCollection.splice(meshIndex, 1);
  84176. }
  84177. };
  84178. /**
  84179. * Enables interactions and teleportation using the VR controllers and gaze.
  84180. * @param vrTeleportationOptions options to modify teleportation behavior.
  84181. */
  84182. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  84183. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  84184. if (!this._teleportationInitialized) {
  84185. this._teleportationRequested = true;
  84186. this.enableInteractions();
  84187. if (vrTeleportationOptions.floorMeshName) {
  84188. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  84189. }
  84190. if (vrTeleportationOptions.floorMeshes) {
  84191. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  84192. }
  84193. if (this.leftController != null) {
  84194. this._enableTeleportationOnController(this.leftController);
  84195. }
  84196. if (this.rightController != null) {
  84197. this._enableTeleportationOnController(this.rightController);
  84198. }
  84199. // Creates an image processing post process for the vignette not relying
  84200. // on the main scene configuration for image processing to reduce setup and spaces
  84201. // (gamma/linear) conflicts.
  84202. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  84203. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  84204. imageProcessingConfiguration.vignetteEnabled = true;
  84205. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  84206. this._webVRCamera.detachPostProcess(this._postProcessMove);
  84207. this._teleportationInitialized = true;
  84208. if (this._isDefaultTeleportationTarget) {
  84209. this._createTeleportationCircles();
  84210. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  84211. }
  84212. }
  84213. };
  84214. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  84215. var _this = this;
  84216. var controllerMesh = controller.webVRController.mesh;
  84217. if (controllerMesh) {
  84218. controller._interactionsEnabled = true;
  84219. controller._activatePointer();
  84220. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  84221. // Enabling / disabling laserPointer
  84222. if (_this._displayLaserPointer && stateObject.value === 1) {
  84223. if (controller._activePointer) {
  84224. controller._deactivatePointer();
  84225. }
  84226. else {
  84227. controller._activatePointer();
  84228. }
  84229. if (_this.displayGaze) {
  84230. controller._gazeTracker.isVisible = controller._activePointer;
  84231. }
  84232. }
  84233. });
  84234. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  84235. if (!controller._pointerDownOnMeshAsked) {
  84236. if (stateObject.value > _this._padSensibilityUp) {
  84237. controller._selectionPointerDown();
  84238. }
  84239. }
  84240. else if (stateObject.value < _this._padSensibilityDown) {
  84241. controller._selectionPointerUp();
  84242. }
  84243. });
  84244. }
  84245. };
  84246. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  84247. // Dont teleport if another gaze already requested teleportation
  84248. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  84249. return;
  84250. }
  84251. if (!gazer._teleportationRequestInitiated) {
  84252. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  84253. gazer._activatePointer();
  84254. gazer._teleportationRequestInitiated = true;
  84255. }
  84256. }
  84257. else {
  84258. // Listening to the proper controller values changes to confirm teleportation
  84259. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  84260. if (this._teleportActive) {
  84261. this._teleportCamera(this._haloCenter);
  84262. }
  84263. gazer._teleportationRequestInitiated = false;
  84264. }
  84265. }
  84266. };
  84267. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  84268. // Only rotate when user is not currently selecting a teleportation location
  84269. if (gazer._teleportationRequestInitiated) {
  84270. return;
  84271. }
  84272. if (!this._rotationLeftAsked) {
  84273. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  84274. this._rotationLeftAsked = true;
  84275. if (this._rotationAllowed) {
  84276. this._rotateCamera(false);
  84277. }
  84278. }
  84279. }
  84280. else {
  84281. if (stateObject.x > -this._padSensibilityDown) {
  84282. this._rotationLeftAsked = false;
  84283. }
  84284. }
  84285. if (!this._rotationRightAsked) {
  84286. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  84287. this._rotationRightAsked = true;
  84288. if (this._rotationAllowed) {
  84289. this._rotateCamera(true);
  84290. }
  84291. }
  84292. }
  84293. else {
  84294. if (stateObject.x < this._padSensibilityDown) {
  84295. this._rotationRightAsked = false;
  84296. }
  84297. }
  84298. };
  84299. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  84300. // Only teleport backwards when user is not currently selecting a teleportation location
  84301. if (gazer._teleportationRequestInitiated) {
  84302. return;
  84303. }
  84304. // Teleport backwards
  84305. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  84306. if (!gazer._teleportationBackRequestInitiated) {
  84307. if (!this.currentVRCamera) {
  84308. return;
  84309. }
  84310. // Get rotation and position of the current camera
  84311. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  84312. var position = this.currentVRCamera.position;
  84313. // If the camera has device position, use that instead
  84314. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  84315. rotation = this.currentVRCamera.deviceRotationQuaternion;
  84316. position = this.currentVRCamera.devicePosition;
  84317. }
  84318. // Get matrix with only the y rotation of the device rotation
  84319. rotation.toEulerAnglesToRef(this._workingVector);
  84320. this._workingVector.z = 0;
  84321. this._workingVector.x = 0;
  84322. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  84323. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  84324. // Rotate backwards ray by device rotation to cast at the ground behind the user
  84325. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  84326. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  84327. var ray = new BABYLON.Ray(position, this._workingVector);
  84328. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  84329. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  84330. this._teleportCamera(hit.pickedPoint);
  84331. }
  84332. gazer._teleportationBackRequestInitiated = true;
  84333. }
  84334. }
  84335. else {
  84336. gazer._teleportationBackRequestInitiated = false;
  84337. }
  84338. };
  84339. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  84340. var _this = this;
  84341. var controllerMesh = controller.webVRController.mesh;
  84342. if (controllerMesh) {
  84343. if (!controller._interactionsEnabled) {
  84344. this._enableInteractionOnController(controller);
  84345. }
  84346. controller._interactionsEnabled = true;
  84347. controller._teleportationEnabled = true;
  84348. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  84349. controller._dpadPressed = false;
  84350. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  84351. controller._dpadPressed = stateObject.pressed;
  84352. if (!controller._dpadPressed) {
  84353. _this._rotationLeftAsked = false;
  84354. _this._rotationRightAsked = false;
  84355. controller._teleportationBackRequestInitiated = false;
  84356. }
  84357. });
  84358. }
  84359. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  84360. if (_this.teleportationEnabled) {
  84361. _this._checkTeleportBackwards(stateObject, controller);
  84362. _this._checkTeleportWithRay(stateObject, controller);
  84363. }
  84364. _this._checkRotate(stateObject, controller);
  84365. });
  84366. }
  84367. };
  84368. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  84369. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  84370. this._teleportationTarget.isPickable = false;
  84371. var length = 512;
  84372. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  84373. dynamicTexture.hasAlpha = true;
  84374. var context = dynamicTexture.getContext();
  84375. var centerX = length / 2;
  84376. var centerY = length / 2;
  84377. var radius = 200;
  84378. context.beginPath();
  84379. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  84380. context.fillStyle = this._teleportationFillColor;
  84381. context.fill();
  84382. context.lineWidth = 10;
  84383. context.strokeStyle = this._teleportationBorderColor;
  84384. context.stroke();
  84385. context.closePath();
  84386. dynamicTexture.update();
  84387. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  84388. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  84389. this._teleportationTarget.material = teleportationCircleMaterial;
  84390. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  84391. torus.isPickable = false;
  84392. torus.parent = this._teleportationTarget;
  84393. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  84394. var keys = [];
  84395. keys.push({
  84396. frame: 0,
  84397. value: 0
  84398. });
  84399. keys.push({
  84400. frame: 30,
  84401. value: 0.4
  84402. });
  84403. keys.push({
  84404. frame: 60,
  84405. value: 0
  84406. });
  84407. animationInnerCircle.setKeys(keys);
  84408. var easingFunction = new BABYLON.SineEase();
  84409. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  84410. animationInnerCircle.setEasingFunction(easingFunction);
  84411. torus.animations = [];
  84412. torus.animations.push(animationInnerCircle);
  84413. this._scene.beginAnimation(torus, 0, 60, true);
  84414. this._hideTeleportationTarget();
  84415. };
  84416. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  84417. this._teleportActive = true;
  84418. if (this._teleportationInitialized) {
  84419. this._teleportationTarget.isVisible = true;
  84420. if (this._isDefaultTeleportationTarget) {
  84421. this._teleportationTarget.getChildren()[0].isVisible = true;
  84422. }
  84423. }
  84424. };
  84425. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  84426. this._teleportActive = false;
  84427. if (this._teleportationInitialized) {
  84428. this._teleportationTarget.isVisible = false;
  84429. if (this._isDefaultTeleportationTarget) {
  84430. this._teleportationTarget.getChildren()[0].isVisible = false;
  84431. }
  84432. }
  84433. };
  84434. VRExperienceHelper.prototype._rotateCamera = function (right) {
  84435. var _this = this;
  84436. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84437. return;
  84438. }
  84439. if (right) {
  84440. this._rotationAngle++;
  84441. }
  84442. else {
  84443. this._rotationAngle--;
  84444. }
  84445. this.currentVRCamera.animations = [];
  84446. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  84447. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84448. var animationRotationKeys = [];
  84449. animationRotationKeys.push({
  84450. frame: 0,
  84451. value: this.currentVRCamera.rotationQuaternion
  84452. });
  84453. animationRotationKeys.push({
  84454. frame: 6,
  84455. value: target
  84456. });
  84457. animationRotation.setKeys(animationRotationKeys);
  84458. animationRotation.setEasingFunction(this._circleEase);
  84459. this.currentVRCamera.animations.push(animationRotation);
  84460. this._postProcessMove.animations = [];
  84461. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84462. var vignetteWeightKeys = [];
  84463. vignetteWeightKeys.push({
  84464. frame: 0,
  84465. value: 0
  84466. });
  84467. vignetteWeightKeys.push({
  84468. frame: 3,
  84469. value: 4
  84470. });
  84471. vignetteWeightKeys.push({
  84472. frame: 6,
  84473. value: 0
  84474. });
  84475. animationPP.setKeys(vignetteWeightKeys);
  84476. animationPP.setEasingFunction(this._circleEase);
  84477. this._postProcessMove.animations.push(animationPP);
  84478. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84479. var vignetteStretchKeys = [];
  84480. vignetteStretchKeys.push({
  84481. frame: 0,
  84482. value: 0
  84483. });
  84484. vignetteStretchKeys.push({
  84485. frame: 3,
  84486. value: 10
  84487. });
  84488. vignetteStretchKeys.push({
  84489. frame: 6,
  84490. value: 0
  84491. });
  84492. animationPP2.setKeys(vignetteStretchKeys);
  84493. animationPP2.setEasingFunction(this._circleEase);
  84494. this._postProcessMove.animations.push(animationPP2);
  84495. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84496. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84497. this._postProcessMove.samples = 4;
  84498. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84499. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  84500. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84501. });
  84502. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  84503. };
  84504. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  84505. if (hit.pickedPoint) {
  84506. if (gazer._teleportationRequestInitiated) {
  84507. this._displayTeleportationTarget();
  84508. this._haloCenter.copyFrom(hit.pickedPoint);
  84509. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  84510. }
  84511. var pickNormal = hit.getNormal(true, false);
  84512. if (pickNormal) {
  84513. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84514. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84515. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  84516. }
  84517. this._teleportationTarget.position.y += 0.1;
  84518. }
  84519. };
  84520. VRExperienceHelper.prototype._teleportCamera = function (location) {
  84521. var _this = this;
  84522. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84523. return;
  84524. }
  84525. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  84526. // offset of the headset from the anchor.
  84527. if (this.webVRCamera.leftCamera) {
  84528. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  84529. this._workingVector.subtractInPlace(this.webVRCamera.position);
  84530. location.subtractToRef(this._workingVector, this._workingVector);
  84531. }
  84532. else {
  84533. this._workingVector.copyFrom(location);
  84534. }
  84535. // Add height to account for user's height offset
  84536. if (this.isInVRMode) {
  84537. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  84538. }
  84539. else {
  84540. this._workingVector.y += this._defaultHeight;
  84541. }
  84542. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  84543. // Create animation from the camera's position to the new location
  84544. this.currentVRCamera.animations = [];
  84545. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84546. var animationCameraTeleportationKeys = [{
  84547. frame: 0,
  84548. value: this.currentVRCamera.position
  84549. },
  84550. {
  84551. frame: 11,
  84552. value: this._workingVector
  84553. }
  84554. ];
  84555. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  84556. animationCameraTeleportation.setEasingFunction(this._circleEase);
  84557. this.currentVRCamera.animations.push(animationCameraTeleportation);
  84558. this._postProcessMove.animations = [];
  84559. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84560. var vignetteWeightKeys = [];
  84561. vignetteWeightKeys.push({
  84562. frame: 0,
  84563. value: 0
  84564. });
  84565. vignetteWeightKeys.push({
  84566. frame: 5,
  84567. value: 8
  84568. });
  84569. vignetteWeightKeys.push({
  84570. frame: 11,
  84571. value: 0
  84572. });
  84573. animationPP.setKeys(vignetteWeightKeys);
  84574. this._postProcessMove.animations.push(animationPP);
  84575. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84576. var vignetteStretchKeys = [];
  84577. vignetteStretchKeys.push({
  84578. frame: 0,
  84579. value: 0
  84580. });
  84581. vignetteStretchKeys.push({
  84582. frame: 5,
  84583. value: 10
  84584. });
  84585. vignetteStretchKeys.push({
  84586. frame: 11,
  84587. value: 0
  84588. });
  84589. animationPP2.setKeys(vignetteStretchKeys);
  84590. this._postProcessMove.animations.push(animationPP2);
  84591. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84592. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84593. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84594. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  84595. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84596. });
  84597. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  84598. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  84599. });
  84600. this._hideTeleportationTarget();
  84601. };
  84602. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  84603. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84604. return;
  84605. }
  84606. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  84607. // Moving the gazeTracker on the mesh face targetted
  84608. if (hit && hit.pickedPoint) {
  84609. if (this._displayGaze) {
  84610. var multiplier = 1;
  84611. gazer._gazeTracker.isVisible = true;
  84612. if (gazer._isActionableMesh) {
  84613. multiplier = 3;
  84614. }
  84615. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  84616. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  84617. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  84618. var pickNormal = hit.getNormal();
  84619. // To avoid z-fighting
  84620. var deltaFighting = 0.002;
  84621. if (pickNormal) {
  84622. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84623. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84624. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  84625. }
  84626. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  84627. if (gazer._gazeTracker.position.x < 0) {
  84628. gazer._gazeTracker.position.x += deltaFighting;
  84629. }
  84630. else {
  84631. gazer._gazeTracker.position.x -= deltaFighting;
  84632. }
  84633. if (gazer._gazeTracker.position.y < 0) {
  84634. gazer._gazeTracker.position.y += deltaFighting;
  84635. }
  84636. else {
  84637. gazer._gazeTracker.position.y -= deltaFighting;
  84638. }
  84639. if (gazer._gazeTracker.position.z < 0) {
  84640. gazer._gazeTracker.position.z += deltaFighting;
  84641. }
  84642. else {
  84643. gazer._gazeTracker.position.z -= deltaFighting;
  84644. }
  84645. }
  84646. // Changing the size of the laser pointer based on the distance from the targetted point
  84647. gazer._updatePointerDistance(hit.distance);
  84648. }
  84649. else {
  84650. gazer._gazeTracker.isVisible = false;
  84651. }
  84652. if (hit && hit.pickedMesh) {
  84653. gazer._currentHit = hit;
  84654. if (gazer._pointerDownOnMeshAsked) {
  84655. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  84656. }
  84657. // The object selected is the floor, we're in a teleportation scenario
  84658. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  84659. // Moving the teleportation area to this targetted point
  84660. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  84661. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  84662. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84663. }
  84664. gazer._currentMeshSelected = null;
  84665. if (gazer._teleportationRequestInitiated) {
  84666. this._moveTeleportationSelectorTo(hit, gazer);
  84667. }
  84668. return;
  84669. }
  84670. // If not, we're in a selection scenario
  84671. //this._teleportationAllowed = false;
  84672. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  84673. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  84674. this.onNewMeshPicked.notifyObservers(hit);
  84675. gazer._currentMeshSelected = hit.pickedMesh;
  84676. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  84677. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  84678. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  84679. gazer._isActionableMesh = true;
  84680. }
  84681. else {
  84682. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84683. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84684. gazer._isActionableMesh = false;
  84685. }
  84686. try {
  84687. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  84688. }
  84689. catch (err) {
  84690. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  84691. }
  84692. }
  84693. else {
  84694. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84695. gazer._currentMeshSelected = null;
  84696. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84697. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84698. }
  84699. }
  84700. }
  84701. else {
  84702. gazer._currentHit = null;
  84703. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84704. gazer._currentMeshSelected = null;
  84705. //this._teleportationAllowed = false;
  84706. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84707. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84708. }
  84709. };
  84710. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  84711. if (mesh) {
  84712. this.onSelectedMeshUnselected.notifyObservers(mesh);
  84713. }
  84714. };
  84715. /**
  84716. * Sets the color of the laser ray from the vr controllers.
  84717. * @param color new color for the ray.
  84718. */
  84719. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  84720. if (this.leftController) {
  84721. this.leftController._setLaserPointerColor(color);
  84722. }
  84723. if (this.rightController) {
  84724. this.rightController._setLaserPointerColor(color);
  84725. }
  84726. };
  84727. /**
  84728. * Sets the color of the ray from the vr headsets gaze.
  84729. * @param color new color for the ray.
  84730. */
  84731. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84732. if (!this._cameraGazer._gazeTracker.material) {
  84733. return;
  84734. }
  84735. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84736. if (this.leftController) {
  84737. this.leftController._gazeTracker.material.emissiveColor = color;
  84738. }
  84739. if (this.rightController) {
  84740. this.rightController._gazeTracker.material.emissiveColor = color;
  84741. }
  84742. };
  84743. /**
  84744. * Exits VR and disposes of the vr experience helper
  84745. */
  84746. VRExperienceHelper.prototype.dispose = function () {
  84747. if (this.isInVRMode) {
  84748. this.exitVR();
  84749. }
  84750. if (this._postProcessMove) {
  84751. this._postProcessMove.dispose();
  84752. }
  84753. if (this._webVRCamera) {
  84754. this._webVRCamera.dispose();
  84755. }
  84756. if (this._vrDeviceOrientationCamera) {
  84757. this._vrDeviceOrientationCamera.dispose();
  84758. }
  84759. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84760. document.body.removeChild(this._btnVR);
  84761. }
  84762. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84763. this._deviceOrientationCamera.dispose();
  84764. }
  84765. if (this._cameraGazer) {
  84766. this._cameraGazer.dispose();
  84767. }
  84768. if (this.leftController) {
  84769. this.leftController.dispose();
  84770. }
  84771. if (this.rightController) {
  84772. this.rightController.dispose();
  84773. }
  84774. if (this._teleportationTarget) {
  84775. this._teleportationTarget.dispose();
  84776. }
  84777. this._floorMeshesCollection = [];
  84778. document.removeEventListener("keydown", this._onKeyDown);
  84779. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84780. window.removeEventListener("resize", this._onResize);
  84781. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84782. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84783. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84784. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84785. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84786. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84787. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84788. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84789. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84790. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84791. this._scene.unregisterBeforeRender(this.beforeRender);
  84792. };
  84793. /**
  84794. * Gets the name of the VRExperienceHelper class
  84795. * @returns "VRExperienceHelper"
  84796. */
  84797. VRExperienceHelper.prototype.getClassName = function () {
  84798. return "VRExperienceHelper";
  84799. };
  84800. return VRExperienceHelper;
  84801. }());
  84802. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84803. })(BABYLON || (BABYLON = {}));
  84804. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84805. "use strict";
  84806. // Mainly based on these 2 articles :
  84807. // 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
  84808. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84809. var BABYLON;
  84810. (function (BABYLON) {
  84811. var JoystickAxis;
  84812. (function (JoystickAxis) {
  84813. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84814. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84815. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84816. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84817. var VirtualJoystick = /** @class */ (function () {
  84818. function VirtualJoystick(leftJoystick) {
  84819. var _this = this;
  84820. if (leftJoystick) {
  84821. this._leftJoystick = true;
  84822. }
  84823. else {
  84824. this._leftJoystick = false;
  84825. }
  84826. VirtualJoystick._globalJoystickIndex++;
  84827. // By default left & right arrow keys are moving the X
  84828. // and up & down keys are moving the Y
  84829. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84830. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84831. this.reverseLeftRight = false;
  84832. this.reverseUpDown = false;
  84833. // collections of pointers
  84834. this._touches = new BABYLON.StringDictionary();
  84835. this.deltaPosition = BABYLON.Vector3.Zero();
  84836. this._joystickSensibility = 25;
  84837. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84838. this._onResize = function (evt) {
  84839. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84840. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84841. if (VirtualJoystick.vjCanvas) {
  84842. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84843. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84844. }
  84845. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84846. };
  84847. // injecting a canvas element on top of the canvas 3D game
  84848. if (!VirtualJoystick.vjCanvas) {
  84849. window.addEventListener("resize", this._onResize, false);
  84850. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84851. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84852. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84853. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84854. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84855. VirtualJoystick.vjCanvas.style.width = "100%";
  84856. VirtualJoystick.vjCanvas.style.height = "100%";
  84857. VirtualJoystick.vjCanvas.style.position = "absolute";
  84858. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84859. VirtualJoystick.vjCanvas.style.top = "0px";
  84860. VirtualJoystick.vjCanvas.style.left = "0px";
  84861. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84862. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84863. // Support for jQuery PEP polyfill
  84864. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84865. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84866. if (!context) {
  84867. throw new Error("Unable to create canvas for virtual joystick");
  84868. }
  84869. VirtualJoystick.vjCanvasContext = context;
  84870. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84871. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84872. document.body.appendChild(VirtualJoystick.vjCanvas);
  84873. }
  84874. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84875. this.pressed = false;
  84876. // default joystick color
  84877. this._joystickColor = "cyan";
  84878. this._joystickPointerID = -1;
  84879. // current joystick position
  84880. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84881. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84882. // origin joystick position
  84883. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84884. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84885. this._onPointerDownHandlerRef = function (evt) {
  84886. _this._onPointerDown(evt);
  84887. };
  84888. this._onPointerMoveHandlerRef = function (evt) {
  84889. _this._onPointerMove(evt);
  84890. };
  84891. this._onPointerUpHandlerRef = function (evt) {
  84892. _this._onPointerUp(evt);
  84893. };
  84894. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84895. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84896. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84897. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84898. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84899. evt.preventDefault(); // Disables system menu
  84900. }, false);
  84901. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84902. }
  84903. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84904. this._joystickSensibility = newJoystickSensibility;
  84905. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84906. };
  84907. VirtualJoystick.prototype._onPointerDown = function (e) {
  84908. var positionOnScreenCondition;
  84909. e.preventDefault();
  84910. if (this._leftJoystick === true) {
  84911. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84912. }
  84913. else {
  84914. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84915. }
  84916. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84917. // First contact will be dedicated to the virtual joystick
  84918. this._joystickPointerID = e.pointerId;
  84919. this._joystickPointerStartPos.x = e.clientX;
  84920. this._joystickPointerStartPos.y = e.clientY;
  84921. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84922. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84923. this._deltaJoystickVector.x = 0;
  84924. this._deltaJoystickVector.y = 0;
  84925. this.pressed = true;
  84926. this._touches.add(e.pointerId.toString(), e);
  84927. }
  84928. else {
  84929. // You can only trigger the action buttons with a joystick declared
  84930. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84931. this._action();
  84932. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84933. }
  84934. }
  84935. };
  84936. VirtualJoystick.prototype._onPointerMove = function (e) {
  84937. // If the current pointer is the one associated to the joystick (first touch contact)
  84938. if (this._joystickPointerID == e.pointerId) {
  84939. this._joystickPointerPos.x = e.clientX;
  84940. this._joystickPointerPos.y = e.clientY;
  84941. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84942. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84943. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84944. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84945. switch (this._axisTargetedByLeftAndRight) {
  84946. case JoystickAxis.X:
  84947. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84948. break;
  84949. case JoystickAxis.Y:
  84950. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84951. break;
  84952. case JoystickAxis.Z:
  84953. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84954. break;
  84955. }
  84956. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84957. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84958. switch (this._axisTargetedByUpAndDown) {
  84959. case JoystickAxis.X:
  84960. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84961. break;
  84962. case JoystickAxis.Y:
  84963. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84964. break;
  84965. case JoystickAxis.Z:
  84966. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84967. break;
  84968. }
  84969. }
  84970. else {
  84971. var data = this._touches.get(e.pointerId.toString());
  84972. if (data) {
  84973. data.x = e.clientX;
  84974. data.y = e.clientY;
  84975. }
  84976. }
  84977. };
  84978. VirtualJoystick.prototype._onPointerUp = function (e) {
  84979. if (this._joystickPointerID == e.pointerId) {
  84980. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84981. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84982. this._joystickPointerID = -1;
  84983. this.pressed = false;
  84984. }
  84985. else {
  84986. var touch = this._touches.get(e.pointerId.toString());
  84987. if (touch) {
  84988. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84989. }
  84990. }
  84991. this._deltaJoystickVector.x = 0;
  84992. this._deltaJoystickVector.y = 0;
  84993. this._touches.remove(e.pointerId.toString());
  84994. };
  84995. /**
  84996. * Change the color of the virtual joystick
  84997. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84998. */
  84999. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  85000. this._joystickColor = newColor;
  85001. };
  85002. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  85003. this._action = action;
  85004. };
  85005. // Define which axis you'd like to control for left & right
  85006. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  85007. switch (axis) {
  85008. case JoystickAxis.X:
  85009. case JoystickAxis.Y:
  85010. case JoystickAxis.Z:
  85011. this._axisTargetedByLeftAndRight = axis;
  85012. break;
  85013. default:
  85014. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  85015. break;
  85016. }
  85017. };
  85018. // Define which axis you'd like to control for up & down
  85019. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  85020. switch (axis) {
  85021. case JoystickAxis.X:
  85022. case JoystickAxis.Y:
  85023. case JoystickAxis.Z:
  85024. this._axisTargetedByUpAndDown = axis;
  85025. break;
  85026. default:
  85027. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  85028. break;
  85029. }
  85030. };
  85031. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  85032. var _this = this;
  85033. if (this.pressed) {
  85034. this._touches.forEach(function (key, touch) {
  85035. if (touch.pointerId === _this._joystickPointerID) {
  85036. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  85037. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  85038. VirtualJoystick.vjCanvasContext.beginPath();
  85039. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  85040. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  85041. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  85042. VirtualJoystick.vjCanvasContext.stroke();
  85043. VirtualJoystick.vjCanvasContext.closePath();
  85044. VirtualJoystick.vjCanvasContext.beginPath();
  85045. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  85046. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  85047. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  85048. VirtualJoystick.vjCanvasContext.stroke();
  85049. VirtualJoystick.vjCanvasContext.closePath();
  85050. VirtualJoystick.vjCanvasContext.beginPath();
  85051. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  85052. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  85053. VirtualJoystick.vjCanvasContext.stroke();
  85054. VirtualJoystick.vjCanvasContext.closePath();
  85055. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  85056. }
  85057. else {
  85058. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  85059. VirtualJoystick.vjCanvasContext.beginPath();
  85060. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  85061. VirtualJoystick.vjCanvasContext.beginPath();
  85062. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  85063. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  85064. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  85065. VirtualJoystick.vjCanvasContext.stroke();
  85066. VirtualJoystick.vjCanvasContext.closePath();
  85067. touch.prevX = touch.x;
  85068. touch.prevY = touch.y;
  85069. }
  85070. ;
  85071. });
  85072. }
  85073. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  85074. };
  85075. VirtualJoystick.prototype.releaseCanvas = function () {
  85076. if (VirtualJoystick.vjCanvas) {
  85077. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  85078. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  85079. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  85080. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  85081. window.removeEventListener("resize", this._onResize);
  85082. document.body.removeChild(VirtualJoystick.vjCanvas);
  85083. VirtualJoystick.vjCanvas = null;
  85084. }
  85085. };
  85086. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  85087. VirtualJoystick._globalJoystickIndex = 0;
  85088. return VirtualJoystick;
  85089. }());
  85090. BABYLON.VirtualJoystick = VirtualJoystick;
  85091. })(BABYLON || (BABYLON = {}));
  85092. //# sourceMappingURL=babylon.virtualJoystick.js.map
  85093. "use strict";
  85094. var BABYLON;
  85095. (function (BABYLON) {
  85096. // We're mainly based on the logic defined into the FreeCamera code
  85097. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  85098. __extends(VirtualJoysticksCamera, _super);
  85099. function VirtualJoysticksCamera(name, position, scene) {
  85100. var _this = _super.call(this, name, position, scene) || this;
  85101. _this.inputs.addVirtualJoystick();
  85102. return _this;
  85103. }
  85104. VirtualJoysticksCamera.prototype.getClassName = function () {
  85105. return "VirtualJoysticksCamera";
  85106. };
  85107. return VirtualJoysticksCamera;
  85108. }(BABYLON.FreeCamera));
  85109. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  85110. })(BABYLON || (BABYLON = {}));
  85111. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  85112. "use strict";
  85113. var BABYLON;
  85114. (function (BABYLON) {
  85115. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  85116. function FreeCameraVirtualJoystickInput() {
  85117. }
  85118. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  85119. return this._leftjoystick;
  85120. };
  85121. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  85122. return this._rightjoystick;
  85123. };
  85124. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  85125. if (this._leftjoystick) {
  85126. var camera = this.camera;
  85127. var speed = camera._computeLocalCameraSpeed() * 50;
  85128. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  85129. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  85130. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  85131. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  85132. if (!this._leftjoystick.pressed) {
  85133. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  85134. }
  85135. if (!this._rightjoystick.pressed) {
  85136. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  85137. }
  85138. }
  85139. };
  85140. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  85141. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  85142. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  85143. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  85144. this._leftjoystick.setJoystickSensibility(0.15);
  85145. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  85146. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  85147. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  85148. this._rightjoystick.reverseUpDown = true;
  85149. this._rightjoystick.setJoystickSensibility(0.05);
  85150. this._rightjoystick.setJoystickColor("yellow");
  85151. };
  85152. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  85153. this._leftjoystick.releaseCanvas();
  85154. this._rightjoystick.releaseCanvas();
  85155. };
  85156. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  85157. return "FreeCameraVirtualJoystickInput";
  85158. };
  85159. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  85160. return "virtualJoystick";
  85161. };
  85162. return FreeCameraVirtualJoystickInput;
  85163. }());
  85164. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  85165. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  85166. })(BABYLON || (BABYLON = {}));
  85167. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  85168. "use strict";
  85169. var BABYLON;
  85170. (function (BABYLON) {
  85171. var SimplificationSettings = /** @class */ (function () {
  85172. function SimplificationSettings(quality, distance, optimizeMesh) {
  85173. this.quality = quality;
  85174. this.distance = distance;
  85175. this.optimizeMesh = optimizeMesh;
  85176. }
  85177. return SimplificationSettings;
  85178. }());
  85179. BABYLON.SimplificationSettings = SimplificationSettings;
  85180. var SimplificationQueue = /** @class */ (function () {
  85181. function SimplificationQueue() {
  85182. this.running = false;
  85183. this._simplificationArray = [];
  85184. }
  85185. SimplificationQueue.prototype.addTask = function (task) {
  85186. this._simplificationArray.push(task);
  85187. };
  85188. SimplificationQueue.prototype.executeNext = function () {
  85189. var task = this._simplificationArray.pop();
  85190. if (task) {
  85191. this.running = true;
  85192. this.runSimplification(task);
  85193. }
  85194. else {
  85195. this.running = false;
  85196. }
  85197. };
  85198. SimplificationQueue.prototype.runSimplification = function (task) {
  85199. var _this = this;
  85200. if (task.parallelProcessing) {
  85201. //parallel simplifier
  85202. task.settings.forEach(function (setting) {
  85203. var simplifier = _this.getSimplifier(task);
  85204. simplifier.simplify(setting, function (newMesh) {
  85205. task.mesh.addLODLevel(setting.distance, newMesh);
  85206. newMesh.isVisible = true;
  85207. //check if it is the last
  85208. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  85209. //all done, run the success callback.
  85210. task.successCallback();
  85211. }
  85212. _this.executeNext();
  85213. });
  85214. });
  85215. }
  85216. else {
  85217. //single simplifier.
  85218. var simplifier = this.getSimplifier(task);
  85219. var runDecimation = function (setting, callback) {
  85220. simplifier.simplify(setting, function (newMesh) {
  85221. task.mesh.addLODLevel(setting.distance, newMesh);
  85222. newMesh.isVisible = true;
  85223. //run the next quality level
  85224. callback();
  85225. });
  85226. };
  85227. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  85228. runDecimation(task.settings[loop.index], function () {
  85229. loop.executeNext();
  85230. });
  85231. }, function () {
  85232. //execution ended, run the success callback.
  85233. if (task.successCallback) {
  85234. task.successCallback();
  85235. }
  85236. _this.executeNext();
  85237. });
  85238. }
  85239. };
  85240. SimplificationQueue.prototype.getSimplifier = function (task) {
  85241. switch (task.simplificationType) {
  85242. case SimplificationType.QUADRATIC:
  85243. default:
  85244. return new QuadraticErrorSimplification(task.mesh);
  85245. }
  85246. };
  85247. return SimplificationQueue;
  85248. }());
  85249. BABYLON.SimplificationQueue = SimplificationQueue;
  85250. /**
  85251. * The implemented types of simplification.
  85252. * At the moment only Quadratic Error Decimation is implemented.
  85253. */
  85254. var SimplificationType;
  85255. (function (SimplificationType) {
  85256. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  85257. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  85258. var DecimationTriangle = /** @class */ (function () {
  85259. function DecimationTriangle(vertices) {
  85260. this.vertices = vertices;
  85261. this.error = new Array(4);
  85262. this.deleted = false;
  85263. this.isDirty = false;
  85264. this.deletePending = false;
  85265. this.borderFactor = 0;
  85266. }
  85267. return DecimationTriangle;
  85268. }());
  85269. BABYLON.DecimationTriangle = DecimationTriangle;
  85270. var DecimationVertex = /** @class */ (function () {
  85271. function DecimationVertex(position, id) {
  85272. this.position = position;
  85273. this.id = id;
  85274. this.isBorder = true;
  85275. this.q = new QuadraticMatrix();
  85276. this.triangleCount = 0;
  85277. this.triangleStart = 0;
  85278. this.originalOffsets = [];
  85279. }
  85280. DecimationVertex.prototype.updatePosition = function (newPosition) {
  85281. this.position.copyFrom(newPosition);
  85282. };
  85283. return DecimationVertex;
  85284. }());
  85285. BABYLON.DecimationVertex = DecimationVertex;
  85286. var QuadraticMatrix = /** @class */ (function () {
  85287. function QuadraticMatrix(data) {
  85288. this.data = new Array(10);
  85289. for (var i = 0; i < 10; ++i) {
  85290. if (data && data[i]) {
  85291. this.data[i] = data[i];
  85292. }
  85293. else {
  85294. this.data[i] = 0;
  85295. }
  85296. }
  85297. }
  85298. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  85299. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  85300. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  85301. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  85302. return det;
  85303. };
  85304. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  85305. for (var i = 0; i < 10; ++i) {
  85306. this.data[i] += matrix.data[i];
  85307. }
  85308. };
  85309. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  85310. for (var i = 0; i < 10; ++i) {
  85311. this.data[i] += data[i];
  85312. }
  85313. };
  85314. QuadraticMatrix.prototype.add = function (matrix) {
  85315. var m = new QuadraticMatrix();
  85316. for (var i = 0; i < 10; ++i) {
  85317. m.data[i] = this.data[i] + matrix.data[i];
  85318. }
  85319. return m;
  85320. };
  85321. QuadraticMatrix.FromData = function (a, b, c, d) {
  85322. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  85323. };
  85324. //returning an array to avoid garbage collection
  85325. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  85326. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  85327. };
  85328. return QuadraticMatrix;
  85329. }());
  85330. BABYLON.QuadraticMatrix = QuadraticMatrix;
  85331. var Reference = /** @class */ (function () {
  85332. function Reference(vertexId, triangleId) {
  85333. this.vertexId = vertexId;
  85334. this.triangleId = triangleId;
  85335. }
  85336. return Reference;
  85337. }());
  85338. BABYLON.Reference = Reference;
  85339. /**
  85340. * An implementation of the Quadratic Error simplification algorithm.
  85341. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  85342. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  85343. * @author RaananW
  85344. */
  85345. var QuadraticErrorSimplification = /** @class */ (function () {
  85346. function QuadraticErrorSimplification(_mesh) {
  85347. this._mesh = _mesh;
  85348. this.syncIterations = 5000;
  85349. this.aggressiveness = 7;
  85350. this.decimationIterations = 100;
  85351. this.boundingBoxEpsilon = BABYLON.Epsilon;
  85352. }
  85353. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  85354. var _this = this;
  85355. this.initDecimatedMesh();
  85356. //iterating through the submeshes array, one after the other.
  85357. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  85358. _this.initWithMesh(loop.index, function () {
  85359. _this.runDecimation(settings, loop.index, function () {
  85360. loop.executeNext();
  85361. });
  85362. }, settings.optimizeMesh);
  85363. }, function () {
  85364. setTimeout(function () {
  85365. successCallback(_this._reconstructedMesh);
  85366. }, 0);
  85367. });
  85368. };
  85369. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  85370. var _this = this;
  85371. var targetCount = ~~(this.triangles.length * settings.quality);
  85372. var deletedTriangles = 0;
  85373. var triangleCount = this.triangles.length;
  85374. var iterationFunction = function (iteration, callback) {
  85375. setTimeout(function () {
  85376. if (iteration % 5 === 0) {
  85377. _this.updateMesh(iteration === 0);
  85378. }
  85379. for (var i = 0; i < _this.triangles.length; ++i) {
  85380. _this.triangles[i].isDirty = false;
  85381. }
  85382. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  85383. var trianglesIterator = function (i) {
  85384. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  85385. var t = _this.triangles[tIdx];
  85386. if (!t)
  85387. return;
  85388. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  85389. return;
  85390. }
  85391. for (var j = 0; j < 3; ++j) {
  85392. if (t.error[j] < threshold) {
  85393. var deleted0 = [];
  85394. var deleted1 = [];
  85395. var v0 = t.vertices[j];
  85396. var v1 = t.vertices[(j + 1) % 3];
  85397. if (v0.isBorder || v1.isBorder)
  85398. continue;
  85399. var p = BABYLON.Vector3.Zero();
  85400. var n = BABYLON.Vector3.Zero();
  85401. var uv = BABYLON.Vector2.Zero();
  85402. var color = new BABYLON.Color4(0, 0, 0, 1);
  85403. _this.calculateError(v0, v1, p, n, uv, color);
  85404. var delTr = new Array();
  85405. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  85406. continue;
  85407. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  85408. continue;
  85409. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  85410. continue;
  85411. var uniqueArray = new Array();
  85412. delTr.forEach(function (deletedT) {
  85413. if (uniqueArray.indexOf(deletedT) === -1) {
  85414. deletedT.deletePending = true;
  85415. uniqueArray.push(deletedT);
  85416. }
  85417. });
  85418. if (uniqueArray.length % 2 !== 0) {
  85419. continue;
  85420. }
  85421. v0.q = v1.q.add(v0.q);
  85422. v0.updatePosition(p);
  85423. var tStart = _this.references.length;
  85424. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  85425. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  85426. var tCount = _this.references.length - tStart;
  85427. if (tCount <= v0.triangleCount) {
  85428. if (tCount) {
  85429. for (var c = 0; c < tCount; c++) {
  85430. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  85431. }
  85432. }
  85433. }
  85434. else {
  85435. v0.triangleStart = tStart;
  85436. }
  85437. v0.triangleCount = tCount;
  85438. break;
  85439. }
  85440. }
  85441. };
  85442. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  85443. }, 0);
  85444. };
  85445. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  85446. if (triangleCount - deletedTriangles <= targetCount)
  85447. loop.breakLoop();
  85448. else {
  85449. iterationFunction(loop.index, function () {
  85450. loop.executeNext();
  85451. });
  85452. }
  85453. }, function () {
  85454. setTimeout(function () {
  85455. //reconstruct this part of the mesh
  85456. _this.reconstructMesh(submeshIndex);
  85457. successCallback();
  85458. }, 0);
  85459. });
  85460. };
  85461. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  85462. var _this = this;
  85463. this.vertices = [];
  85464. this.triangles = [];
  85465. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85466. var indices = this._mesh.getIndices();
  85467. var submesh = this._mesh.subMeshes[submeshIndex];
  85468. var findInVertices = function (positionToSearch) {
  85469. if (optimizeMesh) {
  85470. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  85471. if (_this.vertices[ii].position.equals(positionToSearch)) {
  85472. return _this.vertices[ii];
  85473. }
  85474. }
  85475. }
  85476. return null;
  85477. };
  85478. var vertexReferences = [];
  85479. var vertexInit = function (i) {
  85480. if (!positionData) {
  85481. return;
  85482. }
  85483. var offset = i + submesh.verticesStart;
  85484. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  85485. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  85486. vertex.originalOffsets.push(offset);
  85487. if (vertex.id === _this.vertices.length) {
  85488. _this.vertices.push(vertex);
  85489. }
  85490. vertexReferences.push(vertex.id);
  85491. };
  85492. //var totalVertices = mesh.getTotalVertices();
  85493. var totalVertices = submesh.verticesCount;
  85494. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  85495. var indicesInit = function (i) {
  85496. if (!indices) {
  85497. return;
  85498. }
  85499. var offset = (submesh.indexStart / 3) + i;
  85500. var pos = (offset * 3);
  85501. var i0 = indices[pos + 0];
  85502. var i1 = indices[pos + 1];
  85503. var i2 = indices[pos + 2];
  85504. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  85505. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  85506. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  85507. var triangle = new DecimationTriangle([v0, v1, v2]);
  85508. triangle.originalOffset = pos;
  85509. _this.triangles.push(triangle);
  85510. };
  85511. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  85512. _this.init(callback);
  85513. });
  85514. });
  85515. };
  85516. QuadraticErrorSimplification.prototype.init = function (callback) {
  85517. var _this = this;
  85518. var triangleInit1 = function (i) {
  85519. var t = _this.triangles[i];
  85520. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  85521. for (var j = 0; j < 3; j++) {
  85522. 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))));
  85523. }
  85524. };
  85525. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  85526. var triangleInit2 = function (i) {
  85527. var t = _this.triangles[i];
  85528. for (var j = 0; j < 3; ++j) {
  85529. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  85530. }
  85531. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85532. };
  85533. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  85534. callback();
  85535. });
  85536. });
  85537. };
  85538. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  85539. var newTriangles = [];
  85540. var i;
  85541. for (i = 0; i < this.vertices.length; ++i) {
  85542. this.vertices[i].triangleCount = 0;
  85543. }
  85544. var t;
  85545. var j;
  85546. for (i = 0; i < this.triangles.length; ++i) {
  85547. if (!this.triangles[i].deleted) {
  85548. t = this.triangles[i];
  85549. for (j = 0; j < 3; ++j) {
  85550. t.vertices[j].triangleCount = 1;
  85551. }
  85552. newTriangles.push(t);
  85553. }
  85554. }
  85555. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  85556. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  85557. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  85558. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  85559. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  85560. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85561. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  85562. var vertexCount = 0;
  85563. for (i = 0; i < this.vertices.length; ++i) {
  85564. var vertex = this.vertices[i];
  85565. vertex.id = vertexCount;
  85566. if (vertex.triangleCount) {
  85567. vertex.originalOffsets.forEach(function (originalOffset) {
  85568. if (!normalData) {
  85569. return;
  85570. }
  85571. newPositionData.push(vertex.position.x);
  85572. newPositionData.push(vertex.position.y);
  85573. newPositionData.push(vertex.position.z);
  85574. newNormalData.push(normalData[originalOffset * 3]);
  85575. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  85576. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  85577. if (uvs && uvs.length) {
  85578. newUVsData.push(uvs[(originalOffset * 2)]);
  85579. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  85580. }
  85581. else if (colorsData && colorsData.length) {
  85582. newColorsData.push(colorsData[(originalOffset * 4)]);
  85583. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  85584. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  85585. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  85586. }
  85587. ++vertexCount;
  85588. });
  85589. }
  85590. }
  85591. var startingIndex = this._reconstructedMesh.getTotalIndices();
  85592. var startingVertex = this._reconstructedMesh.getTotalVertices();
  85593. var submeshesArray = this._reconstructedMesh.subMeshes;
  85594. this._reconstructedMesh.subMeshes = [];
  85595. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  85596. var originalIndices = this._mesh.getIndices();
  85597. for (i = 0; i < newTriangles.length; ++i) {
  85598. t = newTriangles[i]; //now get the new referencing point for each vertex
  85599. [0, 1, 2].forEach(function (idx) {
  85600. var id = originalIndices[t.originalOffset + idx];
  85601. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  85602. if (offset < 0)
  85603. offset = 0;
  85604. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  85605. });
  85606. }
  85607. //overwriting the old vertex buffers and indices.
  85608. this._reconstructedMesh.setIndices(newIndicesArray);
  85609. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  85610. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  85611. if (newUVsData.length > 0)
  85612. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  85613. if (newColorsData.length > 0)
  85614. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  85615. //create submesh
  85616. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  85617. if (submeshIndex > 0) {
  85618. this._reconstructedMesh.subMeshes = [];
  85619. submeshesArray.forEach(function (submesh) {
  85620. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  85621. });
  85622. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  85623. }
  85624. };
  85625. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  85626. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  85627. this._reconstructedMesh.material = this._mesh.material;
  85628. this._reconstructedMesh.parent = this._mesh.parent;
  85629. this._reconstructedMesh.isVisible = false;
  85630. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  85631. };
  85632. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  85633. for (var i = 0; i < vertex1.triangleCount; ++i) {
  85634. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  85635. if (t.deleted)
  85636. continue;
  85637. var s = this.references[vertex1.triangleStart + i].vertexId;
  85638. var v1 = t.vertices[(s + 1) % 3];
  85639. var v2 = t.vertices[(s + 2) % 3];
  85640. if ((v1 === vertex2 || v2 === vertex2)) {
  85641. deletedArray[i] = true;
  85642. delTr.push(t);
  85643. continue;
  85644. }
  85645. var d1 = v1.position.subtract(point);
  85646. d1 = d1.normalize();
  85647. var d2 = v2.position.subtract(point);
  85648. d2 = d2.normalize();
  85649. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  85650. return true;
  85651. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  85652. deletedArray[i] = false;
  85653. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  85654. return true;
  85655. }
  85656. return false;
  85657. };
  85658. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  85659. var newDeleted = deletedTriangles;
  85660. for (var i = 0; i < vertex.triangleCount; ++i) {
  85661. var ref = this.references[vertex.triangleStart + i];
  85662. var t = this.triangles[ref.triangleId];
  85663. if (t.deleted)
  85664. continue;
  85665. if (deletedArray[i] && t.deletePending) {
  85666. t.deleted = true;
  85667. newDeleted++;
  85668. continue;
  85669. }
  85670. t.vertices[ref.vertexId] = origVertex;
  85671. t.isDirty = true;
  85672. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  85673. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  85674. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  85675. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85676. this.references.push(ref);
  85677. }
  85678. return newDeleted;
  85679. };
  85680. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  85681. for (var i = 0; i < this.vertices.length; ++i) {
  85682. var vCount = [];
  85683. var vId = [];
  85684. var v = this.vertices[i];
  85685. var j;
  85686. for (j = 0; j < v.triangleCount; ++j) {
  85687. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  85688. for (var ii = 0; ii < 3; ii++) {
  85689. var ofs = 0;
  85690. var vv = triangle.vertices[ii];
  85691. while (ofs < vCount.length) {
  85692. if (vId[ofs] === vv.id)
  85693. break;
  85694. ++ofs;
  85695. }
  85696. if (ofs === vCount.length) {
  85697. vCount.push(1);
  85698. vId.push(vv.id);
  85699. }
  85700. else {
  85701. vCount[ofs]++;
  85702. }
  85703. }
  85704. }
  85705. for (j = 0; j < vCount.length; ++j) {
  85706. if (vCount[j] === 1) {
  85707. this.vertices[vId[j]].isBorder = true;
  85708. }
  85709. else {
  85710. this.vertices[vId[j]].isBorder = false;
  85711. }
  85712. }
  85713. }
  85714. };
  85715. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  85716. if (identifyBorders === void 0) { identifyBorders = false; }
  85717. var i;
  85718. if (!identifyBorders) {
  85719. var newTrianglesVector = [];
  85720. for (i = 0; i < this.triangles.length; ++i) {
  85721. if (!this.triangles[i].deleted) {
  85722. newTrianglesVector.push(this.triangles[i]);
  85723. }
  85724. }
  85725. this.triangles = newTrianglesVector;
  85726. }
  85727. for (i = 0; i < this.vertices.length; ++i) {
  85728. this.vertices[i].triangleCount = 0;
  85729. this.vertices[i].triangleStart = 0;
  85730. }
  85731. var t;
  85732. var j;
  85733. var v;
  85734. for (i = 0; i < this.triangles.length; ++i) {
  85735. t = this.triangles[i];
  85736. for (j = 0; j < 3; ++j) {
  85737. v = t.vertices[j];
  85738. v.triangleCount++;
  85739. }
  85740. }
  85741. var tStart = 0;
  85742. for (i = 0; i < this.vertices.length; ++i) {
  85743. this.vertices[i].triangleStart = tStart;
  85744. tStart += this.vertices[i].triangleCount;
  85745. this.vertices[i].triangleCount = 0;
  85746. }
  85747. var newReferences = new Array(this.triangles.length * 3);
  85748. for (i = 0; i < this.triangles.length; ++i) {
  85749. t = this.triangles[i];
  85750. for (j = 0; j < 3; ++j) {
  85751. v = t.vertices[j];
  85752. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85753. v.triangleCount++;
  85754. }
  85755. }
  85756. this.references = newReferences;
  85757. if (identifyBorders) {
  85758. this.identifyBorder();
  85759. }
  85760. };
  85761. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85762. var x = point.x;
  85763. var y = point.y;
  85764. var z = point.z;
  85765. 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
  85766. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85767. };
  85768. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85769. var q = vertex1.q.add(vertex2.q);
  85770. var border = vertex1.isBorder && vertex2.isBorder;
  85771. var error = 0;
  85772. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85773. if (qDet !== 0 && !border) {
  85774. if (!pointResult) {
  85775. pointResult = BABYLON.Vector3.Zero();
  85776. }
  85777. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85778. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85779. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85780. error = this.vertexError(q, pointResult);
  85781. }
  85782. else {
  85783. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85784. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85785. var error1 = this.vertexError(q, vertex1.position);
  85786. var error2 = this.vertexError(q, vertex2.position);
  85787. var error3 = this.vertexError(q, p3);
  85788. error = Math.min(error1, error2, error3);
  85789. if (error === error1) {
  85790. if (pointResult) {
  85791. pointResult.copyFrom(vertex1.position);
  85792. }
  85793. }
  85794. else if (error === error2) {
  85795. if (pointResult) {
  85796. pointResult.copyFrom(vertex2.position);
  85797. }
  85798. }
  85799. else {
  85800. if (pointResult) {
  85801. pointResult.copyFrom(p3);
  85802. }
  85803. }
  85804. }
  85805. return error;
  85806. };
  85807. return QuadraticErrorSimplification;
  85808. }());
  85809. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85810. })(BABYLON || (BABYLON = {}));
  85811. //# sourceMappingURL=babylon.meshSimplification.js.map
  85812. "use strict";
  85813. var BABYLON;
  85814. (function (BABYLON) {
  85815. var MeshLODLevel = /** @class */ (function () {
  85816. function MeshLODLevel(distance, mesh) {
  85817. this.distance = distance;
  85818. this.mesh = mesh;
  85819. }
  85820. return MeshLODLevel;
  85821. }());
  85822. BABYLON.MeshLODLevel = MeshLODLevel;
  85823. })(BABYLON || (BABYLON = {}));
  85824. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85825. "use strict";
  85826. var BABYLON;
  85827. (function (BABYLON) {
  85828. /**
  85829. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85830. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85831. */
  85832. var SceneOptimization = /** @class */ (function () {
  85833. /**
  85834. * Creates the SceneOptimization object
  85835. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85836. * @param desc defines the description associated with the optimization
  85837. */
  85838. function SceneOptimization(
  85839. /**
  85840. * Defines the priority of this optimization (0 by default which means first in the list)
  85841. */
  85842. priority) {
  85843. if (priority === void 0) { priority = 0; }
  85844. this.priority = priority;
  85845. }
  85846. /**
  85847. * Gets a string describing the action executed by the current optimization
  85848. * @returns description string
  85849. */
  85850. SceneOptimization.prototype.getDescription = function () {
  85851. return "";
  85852. };
  85853. /**
  85854. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85855. * @param scene defines the current scene where to apply this optimization
  85856. * @param optimizer defines the current optimizer
  85857. * @returns true if everything that can be done was applied
  85858. */
  85859. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85860. return true;
  85861. };
  85862. ;
  85863. return SceneOptimization;
  85864. }());
  85865. BABYLON.SceneOptimization = SceneOptimization;
  85866. /**
  85867. * Defines an optimization used to reduce the size of render target textures
  85868. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85869. */
  85870. var TextureOptimization = /** @class */ (function (_super) {
  85871. __extends(TextureOptimization, _super);
  85872. /**
  85873. * Creates the TextureOptimization object
  85874. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85875. * @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
  85876. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85877. */
  85878. function TextureOptimization(
  85879. /**
  85880. * Defines the priority of this optimization (0 by default which means first in the list)
  85881. */
  85882. priority,
  85883. /**
  85884. * 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
  85885. */
  85886. maximumSize,
  85887. /**
  85888. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85889. */
  85890. step) {
  85891. if (priority === void 0) { priority = 0; }
  85892. if (maximumSize === void 0) { maximumSize = 1024; }
  85893. if (step === void 0) { step = 0.5; }
  85894. var _this = _super.call(this, priority) || this;
  85895. _this.priority = priority;
  85896. _this.maximumSize = maximumSize;
  85897. _this.step = step;
  85898. return _this;
  85899. }
  85900. /**
  85901. * Gets a string describing the action executed by the current optimization
  85902. * @returns description string
  85903. */
  85904. TextureOptimization.prototype.getDescription = function () {
  85905. return "Reducing render target texture size to " + this.maximumSize;
  85906. };
  85907. /**
  85908. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85909. * @param scene defines the current scene where to apply this optimization
  85910. * @param optimizer defines the current optimizer
  85911. * @returns true if everything that can be done was applied
  85912. */
  85913. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85914. var allDone = true;
  85915. for (var index = 0; index < scene.textures.length; index++) {
  85916. var texture = scene.textures[index];
  85917. if (!texture.canRescale || texture.getContext) {
  85918. continue;
  85919. }
  85920. var currentSize = texture.getSize();
  85921. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85922. if (maxDimension > this.maximumSize) {
  85923. texture.scale(this.step);
  85924. allDone = false;
  85925. }
  85926. }
  85927. return allDone;
  85928. };
  85929. return TextureOptimization;
  85930. }(SceneOptimization));
  85931. BABYLON.TextureOptimization = TextureOptimization;
  85932. /**
  85933. * Defines an optimization used to increase or decrease the rendering resolution
  85934. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85935. */
  85936. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85937. __extends(HardwareScalingOptimization, _super);
  85938. /**
  85939. * Creates the HardwareScalingOptimization object
  85940. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85941. * @param maximumScale defines the maximum scale to use (2 by default)
  85942. * @param step defines the step to use between two passes (0.5 by default)
  85943. */
  85944. function HardwareScalingOptimization(
  85945. /**
  85946. * Defines the priority of this optimization (0 by default which means first in the list)
  85947. */
  85948. priority,
  85949. /**
  85950. * Defines the maximum scale to use (2 by default)
  85951. */
  85952. maximumScale,
  85953. /**
  85954. * Defines the step to use between two passes (0.5 by default)
  85955. */
  85956. step) {
  85957. if (priority === void 0) { priority = 0; }
  85958. if (maximumScale === void 0) { maximumScale = 2; }
  85959. if (step === void 0) { step = 0.25; }
  85960. var _this = _super.call(this, priority) || this;
  85961. _this.priority = priority;
  85962. _this.maximumScale = maximumScale;
  85963. _this.step = step;
  85964. _this._currentScale = -1;
  85965. _this._directionOffset = 1;
  85966. return _this;
  85967. }
  85968. /**
  85969. * Gets a string describing the action executed by the current optimization
  85970. * @return description string
  85971. */
  85972. HardwareScalingOptimization.prototype.getDescription = function () {
  85973. return "Setting hardware scaling level to " + this._currentScale;
  85974. };
  85975. /**
  85976. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85977. * @param scene defines the current scene where to apply this optimization
  85978. * @param optimizer defines the current optimizer
  85979. * @returns true if everything that can be done was applied
  85980. */
  85981. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85982. if (this._currentScale === -1) {
  85983. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85984. if (this._currentScale > this.maximumScale) {
  85985. this._directionOffset = -1;
  85986. }
  85987. }
  85988. this._currentScale += this._directionOffset * this.step;
  85989. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85990. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85991. };
  85992. ;
  85993. return HardwareScalingOptimization;
  85994. }(SceneOptimization));
  85995. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85996. /**
  85997. * Defines an optimization used to remove shadows
  85998. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85999. */
  86000. var ShadowsOptimization = /** @class */ (function (_super) {
  86001. __extends(ShadowsOptimization, _super);
  86002. function ShadowsOptimization() {
  86003. return _super !== null && _super.apply(this, arguments) || this;
  86004. }
  86005. /**
  86006. * Gets a string describing the action executed by the current optimization
  86007. * @return description string
  86008. */
  86009. ShadowsOptimization.prototype.getDescription = function () {
  86010. return "Turning shadows on/off";
  86011. };
  86012. /**
  86013. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  86014. * @param scene defines the current scene where to apply this optimization
  86015. * @param optimizer defines the current optimizer
  86016. * @returns true if everything that can be done was applied
  86017. */
  86018. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  86019. scene.shadowsEnabled = optimizer.isInImprovementMode;
  86020. return true;
  86021. };
  86022. ;
  86023. return ShadowsOptimization;
  86024. }(SceneOptimization));
  86025. BABYLON.ShadowsOptimization = ShadowsOptimization;
  86026. /**
  86027. * Defines an optimization used to turn post-processes off
  86028. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86029. */
  86030. var PostProcessesOptimization = /** @class */ (function (_super) {
  86031. __extends(PostProcessesOptimization, _super);
  86032. function PostProcessesOptimization() {
  86033. return _super !== null && _super.apply(this, arguments) || this;
  86034. }
  86035. /**
  86036. * Gets a string describing the action executed by the current optimization
  86037. * @return description string
  86038. */
  86039. PostProcessesOptimization.prototype.getDescription = function () {
  86040. return "Turning post-processes on/off";
  86041. };
  86042. /**
  86043. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  86044. * @param scene defines the current scene where to apply this optimization
  86045. * @param optimizer defines the current optimizer
  86046. * @returns true if everything that can be done was applied
  86047. */
  86048. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  86049. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  86050. return true;
  86051. };
  86052. ;
  86053. return PostProcessesOptimization;
  86054. }(SceneOptimization));
  86055. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  86056. /**
  86057. * Defines an optimization used to turn lens flares off
  86058. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86059. */
  86060. var LensFlaresOptimization = /** @class */ (function (_super) {
  86061. __extends(LensFlaresOptimization, _super);
  86062. function LensFlaresOptimization() {
  86063. return _super !== null && _super.apply(this, arguments) || this;
  86064. }
  86065. /**
  86066. * Gets a string describing the action executed by the current optimization
  86067. * @return description string
  86068. */
  86069. LensFlaresOptimization.prototype.getDescription = function () {
  86070. return "Turning lens flares on/off";
  86071. };
  86072. /**
  86073. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  86074. * @param scene defines the current scene where to apply this optimization
  86075. * @param optimizer defines the current optimizer
  86076. * @returns true if everything that can be done was applied
  86077. */
  86078. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  86079. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  86080. return true;
  86081. };
  86082. ;
  86083. return LensFlaresOptimization;
  86084. }(SceneOptimization));
  86085. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  86086. /**
  86087. * Defines an optimization based on user defined callback.
  86088. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86089. */
  86090. var CustomOptimization = /** @class */ (function (_super) {
  86091. __extends(CustomOptimization, _super);
  86092. function CustomOptimization() {
  86093. return _super !== null && _super.apply(this, arguments) || this;
  86094. }
  86095. /**
  86096. * Gets a string describing the action executed by the current optimization
  86097. * @returns description string
  86098. */
  86099. CustomOptimization.prototype.getDescription = function () {
  86100. if (this.onGetDescription) {
  86101. return this.onGetDescription();
  86102. }
  86103. return "Running user defined callback";
  86104. };
  86105. /**
  86106. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  86107. * @param scene defines the current scene where to apply this optimization
  86108. * @param optimizer defines the current optimizer
  86109. * @returns true if everything that can be done was applied
  86110. */
  86111. CustomOptimization.prototype.apply = function (scene, optimizer) {
  86112. if (this.onApply) {
  86113. return this.onApply(scene, optimizer);
  86114. }
  86115. return true;
  86116. };
  86117. ;
  86118. return CustomOptimization;
  86119. }(SceneOptimization));
  86120. BABYLON.CustomOptimization = CustomOptimization;
  86121. /**
  86122. * Defines an optimization used to turn particles off
  86123. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86124. */
  86125. var ParticlesOptimization = /** @class */ (function (_super) {
  86126. __extends(ParticlesOptimization, _super);
  86127. function ParticlesOptimization() {
  86128. return _super !== null && _super.apply(this, arguments) || this;
  86129. }
  86130. /**
  86131. * Gets a string describing the action executed by the current optimization
  86132. * @return description string
  86133. */
  86134. ParticlesOptimization.prototype.getDescription = function () {
  86135. return "Turning particles on/off";
  86136. };
  86137. /**
  86138. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  86139. * @param scene defines the current scene where to apply this optimization
  86140. * @param optimizer defines the current optimizer
  86141. * @returns true if everything that can be done was applied
  86142. */
  86143. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  86144. scene.particlesEnabled = optimizer.isInImprovementMode;
  86145. return true;
  86146. };
  86147. ;
  86148. return ParticlesOptimization;
  86149. }(SceneOptimization));
  86150. BABYLON.ParticlesOptimization = ParticlesOptimization;
  86151. /**
  86152. * Defines an optimization used to turn render targets off
  86153. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86154. */
  86155. var RenderTargetsOptimization = /** @class */ (function (_super) {
  86156. __extends(RenderTargetsOptimization, _super);
  86157. function RenderTargetsOptimization() {
  86158. return _super !== null && _super.apply(this, arguments) || this;
  86159. }
  86160. /**
  86161. * Gets a string describing the action executed by the current optimization
  86162. * @return description string
  86163. */
  86164. RenderTargetsOptimization.prototype.getDescription = function () {
  86165. return "Turning render targets off";
  86166. };
  86167. /**
  86168. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  86169. * @param scene defines the current scene where to apply this optimization
  86170. * @param optimizer defines the current optimizer
  86171. * @returns true if everything that can be done was applied
  86172. */
  86173. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  86174. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  86175. return true;
  86176. };
  86177. ;
  86178. return RenderTargetsOptimization;
  86179. }(SceneOptimization));
  86180. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  86181. /**
  86182. * Defines an optimization used to merge meshes with compatible materials
  86183. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86184. */
  86185. var MergeMeshesOptimization = /** @class */ (function (_super) {
  86186. __extends(MergeMeshesOptimization, _super);
  86187. function MergeMeshesOptimization() {
  86188. var _this = _super !== null && _super.apply(this, arguments) || this;
  86189. _this._canBeMerged = function (abstractMesh) {
  86190. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  86191. return false;
  86192. }
  86193. var mesh = abstractMesh;
  86194. if (!mesh.isVisible || !mesh.isEnabled()) {
  86195. return false;
  86196. }
  86197. if (mesh.instances.length > 0) {
  86198. return false;
  86199. }
  86200. if (mesh.skeleton || mesh.hasLODLevels) {
  86201. return false;
  86202. }
  86203. if (mesh.parent) {
  86204. return false;
  86205. }
  86206. return true;
  86207. };
  86208. return _this;
  86209. }
  86210. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  86211. /**
  86212. * Gets or sets a boolean which defines if optimization octree has to be updated
  86213. */
  86214. get: function () {
  86215. return MergeMeshesOptimization._UpdateSelectionTree;
  86216. },
  86217. /**
  86218. * Gets or sets a boolean which defines if optimization octree has to be updated
  86219. */
  86220. set: function (value) {
  86221. MergeMeshesOptimization._UpdateSelectionTree = value;
  86222. },
  86223. enumerable: true,
  86224. configurable: true
  86225. });
  86226. /**
  86227. * Gets a string describing the action executed by the current optimization
  86228. * @return description string
  86229. */
  86230. MergeMeshesOptimization.prototype.getDescription = function () {
  86231. return "Merging similar meshes together";
  86232. };
  86233. /**
  86234. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  86235. * @param scene defines the current scene where to apply this optimization
  86236. * @param optimizer defines the current optimizer
  86237. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  86238. * @returns true if everything that can be done was applied
  86239. */
  86240. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  86241. var globalPool = scene.meshes.slice(0);
  86242. var globalLength = globalPool.length;
  86243. for (var index = 0; index < globalLength; index++) {
  86244. var currentPool = new Array();
  86245. var current = globalPool[index];
  86246. // Checks
  86247. if (!this._canBeMerged(current)) {
  86248. continue;
  86249. }
  86250. currentPool.push(current);
  86251. // Find compatible meshes
  86252. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  86253. var otherMesh = globalPool[subIndex];
  86254. if (!this._canBeMerged(otherMesh)) {
  86255. continue;
  86256. }
  86257. if (otherMesh.material !== current.material) {
  86258. continue;
  86259. }
  86260. if (otherMesh.checkCollisions !== current.checkCollisions) {
  86261. continue;
  86262. }
  86263. currentPool.push(otherMesh);
  86264. globalLength--;
  86265. globalPool.splice(subIndex, 1);
  86266. subIndex--;
  86267. }
  86268. if (currentPool.length < 2) {
  86269. continue;
  86270. }
  86271. // Merge meshes
  86272. BABYLON.Mesh.MergeMeshes(currentPool);
  86273. }
  86274. if (updateSelectionTree != undefined) {
  86275. if (updateSelectionTree) {
  86276. scene.createOrUpdateSelectionOctree();
  86277. }
  86278. }
  86279. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  86280. scene.createOrUpdateSelectionOctree();
  86281. }
  86282. return true;
  86283. };
  86284. ;
  86285. MergeMeshesOptimization._UpdateSelectionTree = false;
  86286. return MergeMeshesOptimization;
  86287. }(SceneOptimization));
  86288. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  86289. /**
  86290. * Defines a list of options used by SceneOptimizer
  86291. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86292. */
  86293. var SceneOptimizerOptions = /** @class */ (function () {
  86294. /**
  86295. * Creates a new list of options used by SceneOptimizer
  86296. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  86297. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  86298. */
  86299. function SceneOptimizerOptions(
  86300. /**
  86301. * Defines the target frame rate to reach (60 by default)
  86302. */
  86303. targetFrameRate,
  86304. /**
  86305. * Defines the interval between two checkes (2000ms by default)
  86306. */
  86307. trackerDuration) {
  86308. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  86309. if (trackerDuration === void 0) { trackerDuration = 2000; }
  86310. this.targetFrameRate = targetFrameRate;
  86311. this.trackerDuration = trackerDuration;
  86312. /**
  86313. * Gets the list of optimizations to apply
  86314. */
  86315. this.optimizations = new Array();
  86316. }
  86317. /**
  86318. * Add a new optimization
  86319. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  86320. * @returns the current SceneOptimizerOptions
  86321. */
  86322. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  86323. this.optimizations.push(optimization);
  86324. return this;
  86325. };
  86326. /**
  86327. * Add a new custom optimization
  86328. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  86329. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  86330. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  86331. * @returns the current SceneOptimizerOptions
  86332. */
  86333. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  86334. if (priority === void 0) { priority = 0; }
  86335. var optimization = new CustomOptimization(priority);
  86336. optimization.onApply = onApply;
  86337. optimization.onGetDescription = onGetDescription;
  86338. this.optimizations.push(optimization);
  86339. return this;
  86340. };
  86341. /**
  86342. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  86343. * @param targetFrameRate defines the target frame rate (60 by default)
  86344. * @returns a SceneOptimizerOptions object
  86345. */
  86346. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  86347. var result = new SceneOptimizerOptions(targetFrameRate);
  86348. var priority = 0;
  86349. result.addOptimization(new MergeMeshesOptimization(priority));
  86350. result.addOptimization(new ShadowsOptimization(priority));
  86351. result.addOptimization(new LensFlaresOptimization(priority));
  86352. // Next priority
  86353. priority++;
  86354. result.addOptimization(new PostProcessesOptimization(priority));
  86355. result.addOptimization(new ParticlesOptimization(priority));
  86356. // Next priority
  86357. priority++;
  86358. result.addOptimization(new TextureOptimization(priority, 1024));
  86359. return result;
  86360. };
  86361. /**
  86362. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  86363. * @param targetFrameRate defines the target frame rate (60 by default)
  86364. * @returns a SceneOptimizerOptions object
  86365. */
  86366. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  86367. var result = new SceneOptimizerOptions(targetFrameRate);
  86368. var priority = 0;
  86369. result.addOptimization(new MergeMeshesOptimization(priority));
  86370. result.addOptimization(new ShadowsOptimization(priority));
  86371. result.addOptimization(new LensFlaresOptimization(priority));
  86372. // Next priority
  86373. priority++;
  86374. result.addOptimization(new PostProcessesOptimization(priority));
  86375. result.addOptimization(new ParticlesOptimization(priority));
  86376. // Next priority
  86377. priority++;
  86378. result.addOptimization(new TextureOptimization(priority, 512));
  86379. // Next priority
  86380. priority++;
  86381. result.addOptimization(new RenderTargetsOptimization(priority));
  86382. // Next priority
  86383. priority++;
  86384. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  86385. return result;
  86386. };
  86387. /**
  86388. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  86389. * @param targetFrameRate defines the target frame rate (60 by default)
  86390. * @returns a SceneOptimizerOptions object
  86391. */
  86392. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  86393. var result = new SceneOptimizerOptions(targetFrameRate);
  86394. var priority = 0;
  86395. result.addOptimization(new MergeMeshesOptimization(priority));
  86396. result.addOptimization(new ShadowsOptimization(priority));
  86397. result.addOptimization(new LensFlaresOptimization(priority));
  86398. // Next priority
  86399. priority++;
  86400. result.addOptimization(new PostProcessesOptimization(priority));
  86401. result.addOptimization(new ParticlesOptimization(priority));
  86402. // Next priority
  86403. priority++;
  86404. result.addOptimization(new TextureOptimization(priority, 256));
  86405. // Next priority
  86406. priority++;
  86407. result.addOptimization(new RenderTargetsOptimization(priority));
  86408. // Next priority
  86409. priority++;
  86410. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  86411. return result;
  86412. };
  86413. return SceneOptimizerOptions;
  86414. }());
  86415. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  86416. /**
  86417. * Class used to run optimizations in order to reach a target frame rate
  86418. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86419. */
  86420. var SceneOptimizer = /** @class */ (function () {
  86421. /**
  86422. * Creates a new SceneOptimizer
  86423. * @param scene defines the scene to work on
  86424. * @param options defines the options to use with the SceneOptimizer
  86425. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  86426. * @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)
  86427. */
  86428. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  86429. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  86430. if (improvementMode === void 0) { improvementMode = false; }
  86431. var _this = this;
  86432. this._isRunning = false;
  86433. this._currentPriorityLevel = 0;
  86434. this._targetFrameRate = 60;
  86435. this._trackerDuration = 2000;
  86436. this._currentFrameRate = 0;
  86437. this._improvementMode = false;
  86438. /**
  86439. * Defines an observable called when the optimizer reaches the target frame rate
  86440. */
  86441. this.onSuccessObservable = new BABYLON.Observable();
  86442. /**
  86443. * Defines an observable called when the optimizer enables an optimization
  86444. */
  86445. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  86446. /**
  86447. * Defines an observable called when the optimizer is not able to reach the target frame rate
  86448. */
  86449. this.onFailureObservable = new BABYLON.Observable();
  86450. if (!options) {
  86451. this._options = new SceneOptimizerOptions();
  86452. }
  86453. else {
  86454. this._options = options;
  86455. }
  86456. if (this._options.targetFrameRate) {
  86457. this._targetFrameRate = this._options.targetFrameRate;
  86458. }
  86459. if (this._options.trackerDuration) {
  86460. this._trackerDuration = this._options.trackerDuration;
  86461. }
  86462. if (autoGeneratePriorities) {
  86463. var priority = 0;
  86464. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  86465. var optim = _a[_i];
  86466. optim.priority = priority++;
  86467. }
  86468. }
  86469. this._improvementMode = improvementMode;
  86470. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86471. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  86472. _this._sceneDisposeObserver = null;
  86473. _this.dispose();
  86474. });
  86475. }
  86476. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  86477. /**
  86478. * Gets a boolean indicating if the optimizer is in improvement mode
  86479. */
  86480. get: function () {
  86481. return this._improvementMode;
  86482. },
  86483. enumerable: true,
  86484. configurable: true
  86485. });
  86486. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  86487. /**
  86488. * Gets the current priority level (0 at start)
  86489. */
  86490. get: function () {
  86491. return this._currentPriorityLevel;
  86492. },
  86493. enumerable: true,
  86494. configurable: true
  86495. });
  86496. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  86497. /**
  86498. * Gets the current frame rate checked by the SceneOptimizer
  86499. */
  86500. get: function () {
  86501. return this._currentFrameRate;
  86502. },
  86503. enumerable: true,
  86504. configurable: true
  86505. });
  86506. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  86507. /**
  86508. * Gets or sets the current target frame rate (60 by default)
  86509. */
  86510. get: function () {
  86511. return this._targetFrameRate;
  86512. },
  86513. /**
  86514. * Gets or sets the current target frame rate (60 by default)
  86515. */
  86516. set: function (value) {
  86517. this._targetFrameRate = value;
  86518. },
  86519. enumerable: true,
  86520. configurable: true
  86521. });
  86522. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  86523. /**
  86524. * Gets or sets the current interval between two checks (every 2000ms by default)
  86525. */
  86526. get: function () {
  86527. return this._trackerDuration;
  86528. },
  86529. /**
  86530. * Gets or sets the current interval between two checks (every 2000ms by default)
  86531. */
  86532. set: function (value) {
  86533. this._trackerDuration = value;
  86534. },
  86535. enumerable: true,
  86536. configurable: true
  86537. });
  86538. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  86539. /**
  86540. * Gets the list of active optimizations
  86541. */
  86542. get: function () {
  86543. return this._options.optimizations;
  86544. },
  86545. enumerable: true,
  86546. configurable: true
  86547. });
  86548. /**
  86549. * Stops the current optimizer
  86550. */
  86551. SceneOptimizer.prototype.stop = function () {
  86552. this._isRunning = false;
  86553. };
  86554. /**
  86555. * Reset the optimizer to initial step (current priority level = 0)
  86556. */
  86557. SceneOptimizer.prototype.reset = function () {
  86558. this._currentPriorityLevel = 0;
  86559. };
  86560. /**
  86561. * Start the optimizer. By default it will try to reach a specific framerate
  86562. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  86563. */
  86564. SceneOptimizer.prototype.start = function () {
  86565. var _this = this;
  86566. if (this._isRunning) {
  86567. return;
  86568. }
  86569. this._isRunning = true;
  86570. // Let's wait for the scene to be ready before running our check
  86571. this._scene.executeWhenReady(function () {
  86572. setTimeout(function () {
  86573. _this._checkCurrentState();
  86574. }, _this._trackerDuration);
  86575. });
  86576. };
  86577. SceneOptimizer.prototype._checkCurrentState = function () {
  86578. var _this = this;
  86579. if (!this._isRunning) {
  86580. return;
  86581. }
  86582. var scene = this._scene;
  86583. var options = this._options;
  86584. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  86585. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  86586. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  86587. this._isRunning = false;
  86588. this.onSuccessObservable.notifyObservers(this);
  86589. return;
  86590. }
  86591. // Apply current level of optimizations
  86592. var allDone = true;
  86593. var noOptimizationApplied = true;
  86594. for (var index = 0; index < options.optimizations.length; index++) {
  86595. var optimization = options.optimizations[index];
  86596. if (optimization.priority === this._currentPriorityLevel) {
  86597. noOptimizationApplied = false;
  86598. allDone = allDone && optimization.apply(scene, this);
  86599. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  86600. }
  86601. }
  86602. // If no optimization was applied, this is a failure :(
  86603. if (noOptimizationApplied) {
  86604. this._isRunning = false;
  86605. this.onFailureObservable.notifyObservers(this);
  86606. return;
  86607. }
  86608. // If all optimizations were done, move to next level
  86609. if (allDone) {
  86610. this._currentPriorityLevel++;
  86611. }
  86612. // Let's the system running for a specific amount of time before checking FPS
  86613. scene.executeWhenReady(function () {
  86614. setTimeout(function () {
  86615. _this._checkCurrentState();
  86616. }, _this._trackerDuration);
  86617. });
  86618. };
  86619. /**
  86620. * Release all resources
  86621. */
  86622. SceneOptimizer.prototype.dispose = function () {
  86623. this.stop();
  86624. this.onSuccessObservable.clear();
  86625. this.onFailureObservable.clear();
  86626. this.onNewOptimizationAppliedObservable.clear();
  86627. if (this._sceneDisposeObserver) {
  86628. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86629. }
  86630. };
  86631. /**
  86632. * Helper function to create a SceneOptimizer with one single line of code
  86633. * @param scene defines the scene to work on
  86634. * @param options defines the options to use with the SceneOptimizer
  86635. * @param onSuccess defines a callback to call on success
  86636. * @param onFailure defines a callback to call on failure
  86637. * @returns the new SceneOptimizer object
  86638. */
  86639. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  86640. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  86641. if (onSuccess) {
  86642. optimizer.onSuccessObservable.add(function () {
  86643. onSuccess();
  86644. });
  86645. }
  86646. if (onFailure) {
  86647. optimizer.onFailureObservable.add(function () {
  86648. onFailure();
  86649. });
  86650. }
  86651. optimizer.start();
  86652. return optimizer;
  86653. };
  86654. return SceneOptimizer;
  86655. }());
  86656. BABYLON.SceneOptimizer = SceneOptimizer;
  86657. })(BABYLON || (BABYLON = {}));
  86658. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  86659. "use strict";
  86660. var BABYLON;
  86661. (function (BABYLON) {
  86662. var OutlineRenderer = /** @class */ (function () {
  86663. function OutlineRenderer(scene) {
  86664. this.zOffset = 1;
  86665. this._scene = scene;
  86666. }
  86667. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  86668. var _this = this;
  86669. if (useOverlay === void 0) { useOverlay = false; }
  86670. var scene = this._scene;
  86671. var engine = this._scene.getEngine();
  86672. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86673. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  86674. return;
  86675. }
  86676. var mesh = subMesh.getRenderingMesh();
  86677. var material = subMesh.getMaterial();
  86678. if (!material || !scene.activeCamera) {
  86679. return;
  86680. }
  86681. engine.enableEffect(this._effect);
  86682. // Logarithmic depth
  86683. if (material.useLogarithmicDepth) {
  86684. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  86685. }
  86686. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  86687. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  86688. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86689. // Bones
  86690. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86691. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86692. }
  86693. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  86694. // Alpha test
  86695. if (material && material.needAlphaTesting()) {
  86696. var alphaTexture = material.getAlphaTestTexture();
  86697. if (alphaTexture) {
  86698. this._effect.setTexture("diffuseSampler", alphaTexture);
  86699. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86700. }
  86701. }
  86702. engine.setZOffset(-this.zOffset);
  86703. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  86704. engine.setZOffset(0);
  86705. };
  86706. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  86707. var defines = [];
  86708. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86709. var mesh = subMesh.getMesh();
  86710. var material = subMesh.getMaterial();
  86711. if (material) {
  86712. // Alpha test
  86713. if (material.needAlphaTesting()) {
  86714. defines.push("#define ALPHATEST");
  86715. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86716. attribs.push(BABYLON.VertexBuffer.UVKind);
  86717. defines.push("#define UV1");
  86718. }
  86719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86720. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86721. defines.push("#define UV2");
  86722. }
  86723. }
  86724. //Logarithmic depth
  86725. if (material.useLogarithmicDepth) {
  86726. defines.push("#define LOGARITHMICDEPTH");
  86727. }
  86728. }
  86729. // Bones
  86730. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86733. if (mesh.numBoneInfluencers > 4) {
  86734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86736. }
  86737. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86738. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86739. }
  86740. else {
  86741. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86742. }
  86743. // Instances
  86744. if (useInstances) {
  86745. defines.push("#define INSTANCES");
  86746. attribs.push("world0");
  86747. attribs.push("world1");
  86748. attribs.push("world2");
  86749. attribs.push("world3");
  86750. }
  86751. // Get correct effect
  86752. var join = defines.join("\n");
  86753. if (this._cachedDefines !== join) {
  86754. this._cachedDefines = join;
  86755. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86756. }
  86757. return this._effect.isReady();
  86758. };
  86759. return OutlineRenderer;
  86760. }());
  86761. BABYLON.OutlineRenderer = OutlineRenderer;
  86762. })(BABYLON || (BABYLON = {}));
  86763. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86764. "use strict";
  86765. var BABYLON;
  86766. (function (BABYLON) {
  86767. var FaceAdjacencies = /** @class */ (function () {
  86768. function FaceAdjacencies() {
  86769. this.edges = new Array();
  86770. this.edgesConnectedCount = 0;
  86771. }
  86772. return FaceAdjacencies;
  86773. }());
  86774. var EdgesRenderer = /** @class */ (function () {
  86775. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86776. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86777. if (epsilon === void 0) { epsilon = 0.95; }
  86778. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86779. this.edgesWidthScalerForOrthographic = 1000.0;
  86780. this.edgesWidthScalerForPerspective = 50.0;
  86781. this._linesPositions = new Array();
  86782. this._linesNormals = new Array();
  86783. this._linesIndices = new Array();
  86784. this._buffers = {};
  86785. this._checkVerticesInsteadOfIndices = false;
  86786. this._source = source;
  86787. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86788. this._epsilon = epsilon;
  86789. this._prepareRessources();
  86790. this._generateEdgesLines();
  86791. }
  86792. EdgesRenderer.prototype._prepareRessources = function () {
  86793. if (this._lineShader) {
  86794. return;
  86795. }
  86796. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86797. attributes: ["position", "normal"],
  86798. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86799. });
  86800. this._lineShader.disableDepthWrite = true;
  86801. this._lineShader.backFaceCulling = false;
  86802. };
  86803. EdgesRenderer.prototype._rebuild = function () {
  86804. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86805. if (buffer) {
  86806. buffer._rebuild();
  86807. }
  86808. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86809. if (buffer) {
  86810. buffer._rebuild();
  86811. }
  86812. var scene = this._source.getScene();
  86813. var engine = scene.getEngine();
  86814. this._ib = engine.createIndexBuffer(this._linesIndices);
  86815. };
  86816. EdgesRenderer.prototype.dispose = function () {
  86817. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86818. if (buffer) {
  86819. buffer.dispose();
  86820. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86821. }
  86822. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86823. if (buffer) {
  86824. buffer.dispose();
  86825. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86826. }
  86827. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86828. this._lineShader.dispose();
  86829. };
  86830. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86831. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86832. return 0;
  86833. }
  86834. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86835. return 1;
  86836. }
  86837. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86838. return 2;
  86839. }
  86840. return -1;
  86841. };
  86842. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86843. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86844. return 0;
  86845. }
  86846. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86847. return 1;
  86848. }
  86849. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86850. return 2;
  86851. }
  86852. return -1;
  86853. };
  86854. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86855. var needToCreateLine;
  86856. if (edge === undefined) {
  86857. needToCreateLine = true;
  86858. }
  86859. else {
  86860. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86861. needToCreateLine = dotProduct < this._epsilon;
  86862. }
  86863. if (needToCreateLine) {
  86864. var offset = this._linesPositions.length / 3;
  86865. var normal = p0.subtract(p1);
  86866. normal.normalize();
  86867. // Positions
  86868. this._linesPositions.push(p0.x);
  86869. this._linesPositions.push(p0.y);
  86870. this._linesPositions.push(p0.z);
  86871. this._linesPositions.push(p0.x);
  86872. this._linesPositions.push(p0.y);
  86873. this._linesPositions.push(p0.z);
  86874. this._linesPositions.push(p1.x);
  86875. this._linesPositions.push(p1.y);
  86876. this._linesPositions.push(p1.z);
  86877. this._linesPositions.push(p1.x);
  86878. this._linesPositions.push(p1.y);
  86879. this._linesPositions.push(p1.z);
  86880. // Normals
  86881. this._linesNormals.push(p1.x);
  86882. this._linesNormals.push(p1.y);
  86883. this._linesNormals.push(p1.z);
  86884. this._linesNormals.push(-1);
  86885. this._linesNormals.push(p1.x);
  86886. this._linesNormals.push(p1.y);
  86887. this._linesNormals.push(p1.z);
  86888. this._linesNormals.push(1);
  86889. this._linesNormals.push(p0.x);
  86890. this._linesNormals.push(p0.y);
  86891. this._linesNormals.push(p0.z);
  86892. this._linesNormals.push(-1);
  86893. this._linesNormals.push(p0.x);
  86894. this._linesNormals.push(p0.y);
  86895. this._linesNormals.push(p0.z);
  86896. this._linesNormals.push(1);
  86897. // Indices
  86898. this._linesIndices.push(offset);
  86899. this._linesIndices.push(offset + 1);
  86900. this._linesIndices.push(offset + 2);
  86901. this._linesIndices.push(offset);
  86902. this._linesIndices.push(offset + 2);
  86903. this._linesIndices.push(offset + 3);
  86904. }
  86905. };
  86906. EdgesRenderer.prototype._generateEdgesLines = function () {
  86907. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86908. var indices = this._source.getIndices();
  86909. if (!indices || !positions) {
  86910. return;
  86911. }
  86912. // First let's find adjacencies
  86913. var adjacencies = new Array();
  86914. var faceNormals = new Array();
  86915. var index;
  86916. var faceAdjacencies;
  86917. // Prepare faces
  86918. for (index = 0; index < indices.length; index += 3) {
  86919. faceAdjacencies = new FaceAdjacencies();
  86920. var p0Index = indices[index];
  86921. var p1Index = indices[index + 1];
  86922. var p2Index = indices[index + 2];
  86923. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86924. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86925. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86926. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86927. faceNormal.normalize();
  86928. faceNormals.push(faceNormal);
  86929. adjacencies.push(faceAdjacencies);
  86930. }
  86931. // Scan
  86932. for (index = 0; index < adjacencies.length; index++) {
  86933. faceAdjacencies = adjacencies[index];
  86934. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86935. var otherFaceAdjacencies = adjacencies[otherIndex];
  86936. if (faceAdjacencies.edgesConnectedCount === 3) {
  86937. break;
  86938. }
  86939. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86940. continue;
  86941. }
  86942. var otherP0 = indices[otherIndex * 3];
  86943. var otherP1 = indices[otherIndex * 3 + 1];
  86944. var otherP2 = indices[otherIndex * 3 + 2];
  86945. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86946. var otherEdgeIndex = 0;
  86947. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86948. continue;
  86949. }
  86950. switch (edgeIndex) {
  86951. case 0:
  86952. if (this._checkVerticesInsteadOfIndices) {
  86953. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86954. }
  86955. else {
  86956. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86957. }
  86958. break;
  86959. case 1:
  86960. if (this._checkVerticesInsteadOfIndices) {
  86961. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86962. }
  86963. else {
  86964. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86965. }
  86966. break;
  86967. case 2:
  86968. if (this._checkVerticesInsteadOfIndices) {
  86969. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86970. }
  86971. else {
  86972. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86973. }
  86974. break;
  86975. }
  86976. if (otherEdgeIndex === -1) {
  86977. continue;
  86978. }
  86979. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86980. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86981. faceAdjacencies.edgesConnectedCount++;
  86982. otherFaceAdjacencies.edgesConnectedCount++;
  86983. if (faceAdjacencies.edgesConnectedCount === 3) {
  86984. break;
  86985. }
  86986. }
  86987. }
  86988. }
  86989. // Create lines
  86990. for (index = 0; index < adjacencies.length; index++) {
  86991. // 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
  86992. var current = adjacencies[index];
  86993. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86994. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86995. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86996. }
  86997. // Merge into a single mesh
  86998. var engine = this._source.getScene().getEngine();
  86999. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  87000. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  87001. this._ib = engine.createIndexBuffer(this._linesIndices);
  87002. this._indicesCount = this._linesIndices.length;
  87003. };
  87004. EdgesRenderer.prototype.render = function () {
  87005. var scene = this._source.getScene();
  87006. if (!this._lineShader.isReady() || !scene.activeCamera) {
  87007. return;
  87008. }
  87009. var engine = scene.getEngine();
  87010. this._lineShader._preBind();
  87011. // VBOs
  87012. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  87013. scene.resetCachedMaterial();
  87014. this._lineShader.setColor4("color", this._source.edgesColor);
  87015. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  87016. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  87017. }
  87018. else {
  87019. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  87020. }
  87021. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  87022. this._lineShader.bind(this._source.getWorldMatrix());
  87023. // Draw order
  87024. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  87025. this._lineShader.unbind();
  87026. engine.setDepthWrite(true);
  87027. };
  87028. return EdgesRenderer;
  87029. }());
  87030. BABYLON.EdgesRenderer = EdgesRenderer;
  87031. })(BABYLON || (BABYLON = {}));
  87032. //# sourceMappingURL=babylon.edgesRenderer.js.map
  87033. "use strict";
  87034. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87035. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87036. s = arguments[i];
  87037. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87038. t[p] = s[p];
  87039. }
  87040. return t;
  87041. };
  87042. var BABYLON;
  87043. (function (BABYLON) {
  87044. /**
  87045. * The effect layer Helps adding post process effect blended with the main pass.
  87046. *
  87047. * This can be for instance use to generate glow or higlight effects on the scene.
  87048. *
  87049. * The effect layer class can not be used directly and is intented to inherited from to be
  87050. * customized per effects.
  87051. */
  87052. var EffectLayer = /** @class */ (function () {
  87053. /**
  87054. * Instantiates a new effect Layer and references it in the scene.
  87055. * @param name The name of the layer
  87056. * @param scene The scene to use the layer in
  87057. */
  87058. function EffectLayer(
  87059. /** The Friendly of the effect in the scene */
  87060. name, scene) {
  87061. this.name = name;
  87062. this._vertexBuffers = {};
  87063. this._maxSize = 0;
  87064. this._mainTextureDesiredSize = { width: 0, height: 0 };
  87065. this._shouldRender = true;
  87066. this._postProcesses = [];
  87067. this._textures = [];
  87068. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  87069. /**
  87070. * The clear color of the texture used to generate the glow map.
  87071. */
  87072. this.neutralColor = new BABYLON.Color4();
  87073. /**
  87074. * Specifies wether the highlight layer is enabled or not.
  87075. */
  87076. this.isEnabled = true;
  87077. /**
  87078. * An event triggered when the effect layer has been disposed.
  87079. */
  87080. this.onDisposeObservable = new BABYLON.Observable();
  87081. /**
  87082. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  87083. */
  87084. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  87085. /**
  87086. * An event triggered when the generated texture is being merged in the scene.
  87087. */
  87088. this.onBeforeComposeObservable = new BABYLON.Observable();
  87089. /**
  87090. * An event triggered when the generated texture has been merged in the scene.
  87091. */
  87092. this.onAfterComposeObservable = new BABYLON.Observable();
  87093. /**
  87094. * An event triggered when the efffect layer changes its size.
  87095. */
  87096. this.onSizeChangedObservable = new BABYLON.Observable();
  87097. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87098. this._engine = scene.getEngine();
  87099. this._maxSize = this._engine.getCaps().maxTextureSize;
  87100. this._scene.effectLayers.push(this);
  87101. // Generate Buffers
  87102. this._generateIndexBuffer();
  87103. this._genrateVertexBuffer();
  87104. }
  87105. Object.defineProperty(EffectLayer.prototype, "camera", {
  87106. /**
  87107. * Gets the camera attached to the layer.
  87108. */
  87109. get: function () {
  87110. return this._effectLayerOptions.camera;
  87111. },
  87112. enumerable: true,
  87113. configurable: true
  87114. });
  87115. /**
  87116. * Initializes the effect layer with the required options.
  87117. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  87118. */
  87119. EffectLayer.prototype._init = function (options) {
  87120. // Adapt options
  87121. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87122. this._setMainTextureSize();
  87123. this._createMainTexture();
  87124. this._createTextureAndPostProcesses();
  87125. this._mergeEffect = this._createMergeEffect();
  87126. };
  87127. /**
  87128. * Generates the index buffer of the full screen quad blending to the main canvas.
  87129. */
  87130. EffectLayer.prototype._generateIndexBuffer = function () {
  87131. // Indices
  87132. var indices = [];
  87133. indices.push(0);
  87134. indices.push(1);
  87135. indices.push(2);
  87136. indices.push(0);
  87137. indices.push(2);
  87138. indices.push(3);
  87139. this._indexBuffer = this._engine.createIndexBuffer(indices);
  87140. };
  87141. /**
  87142. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  87143. */
  87144. EffectLayer.prototype._genrateVertexBuffer = function () {
  87145. // VBO
  87146. var vertices = [];
  87147. vertices.push(1, 1);
  87148. vertices.push(-1, 1);
  87149. vertices.push(-1, -1);
  87150. vertices.push(1, -1);
  87151. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87152. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87153. };
  87154. /**
  87155. * Sets the main texture desired size which is the closest power of two
  87156. * of the engine canvas size.
  87157. */
  87158. EffectLayer.prototype._setMainTextureSize = function () {
  87159. if (this._effectLayerOptions.mainTextureFixedSize) {
  87160. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  87161. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  87162. }
  87163. else {
  87164. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  87165. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  87166. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  87167. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  87168. }
  87169. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  87170. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  87171. };
  87172. /**
  87173. * Creates the main texture for the effect layer.
  87174. */
  87175. EffectLayer.prototype._createMainTexture = function () {
  87176. var _this = this;
  87177. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  87178. width: this._mainTextureDesiredSize.width,
  87179. height: this._mainTextureDesiredSize.height
  87180. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87181. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  87182. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87183. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87184. this._mainTexture.anisotropicFilteringLevel = 1;
  87185. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87186. this._mainTexture.renderParticles = false;
  87187. this._mainTexture.renderList = null;
  87188. this._mainTexture.ignoreCameraViewport = true;
  87189. // Custom render function
  87190. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  87191. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  87192. var index;
  87193. var engine = _this._scene.getEngine();
  87194. if (depthOnlySubMeshes.length) {
  87195. engine.setColorWrite(false);
  87196. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  87197. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  87198. }
  87199. engine.setColorWrite(true);
  87200. }
  87201. for (index = 0; index < opaqueSubMeshes.length; index++) {
  87202. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  87203. }
  87204. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  87205. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  87206. }
  87207. for (index = 0; index < transparentSubMeshes.length; index++) {
  87208. _this._renderSubMesh(transparentSubMeshes.data[index]);
  87209. }
  87210. };
  87211. this._mainTexture.onClearObservable.add(function (engine) {
  87212. engine.clear(_this.neutralColor, true, true, true);
  87213. });
  87214. };
  87215. /**
  87216. * Checks for the readiness of the element composing the layer.
  87217. * @param subMesh the mesh to check for
  87218. * @param useInstances specify wether or not to use instances to render the mesh
  87219. * @param emissiveTexture the associated emissive texture used to generate the glow
  87220. * @return true if ready otherwise, false
  87221. */
  87222. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  87223. var material = subMesh.getMaterial();
  87224. if (!material) {
  87225. return false;
  87226. }
  87227. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  87228. return false;
  87229. }
  87230. var defines = [];
  87231. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87232. var mesh = subMesh.getMesh();
  87233. var uv1 = false;
  87234. var uv2 = false;
  87235. // Alpha test
  87236. if (material && material.needAlphaTesting()) {
  87237. var alphaTexture = material.getAlphaTestTexture();
  87238. if (alphaTexture) {
  87239. defines.push("#define ALPHATEST");
  87240. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  87241. alphaTexture.coordinatesIndex === 1) {
  87242. defines.push("#define DIFFUSEUV2");
  87243. uv2 = true;
  87244. }
  87245. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87246. defines.push("#define DIFFUSEUV1");
  87247. uv1 = true;
  87248. }
  87249. }
  87250. }
  87251. // Emissive
  87252. if (emissiveTexture) {
  87253. defines.push("#define EMISSIVE");
  87254. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  87255. emissiveTexture.coordinatesIndex === 1) {
  87256. defines.push("#define EMISSIVEUV2");
  87257. uv2 = true;
  87258. }
  87259. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87260. defines.push("#define EMISSIVEUV1");
  87261. uv1 = true;
  87262. }
  87263. }
  87264. if (uv1) {
  87265. attribs.push(BABYLON.VertexBuffer.UVKind);
  87266. defines.push("#define UV1");
  87267. }
  87268. if (uv2) {
  87269. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87270. defines.push("#define UV2");
  87271. }
  87272. // Bones
  87273. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  87274. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  87275. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  87276. if (mesh.numBoneInfluencers > 4) {
  87277. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  87278. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  87279. }
  87280. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  87281. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  87282. }
  87283. else {
  87284. defines.push("#define NUM_BONE_INFLUENCERS 0");
  87285. }
  87286. // Morph targets
  87287. var manager = mesh.morphTargetManager;
  87288. var morphInfluencers = 0;
  87289. if (manager) {
  87290. if (manager.numInfluencers > 0) {
  87291. defines.push("#define MORPHTARGETS");
  87292. morphInfluencers = manager.numInfluencers;
  87293. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  87294. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  87295. }
  87296. }
  87297. // Instances
  87298. if (useInstances) {
  87299. defines.push("#define INSTANCES");
  87300. attribs.push("world0");
  87301. attribs.push("world1");
  87302. attribs.push("world2");
  87303. attribs.push("world3");
  87304. }
  87305. // Get correct effect
  87306. var join = defines.join("\n");
  87307. if (this._cachedDefines !== join) {
  87308. this._cachedDefines = join;
  87309. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  87310. }
  87311. return this._effectLayerMapGenerationEffect.isReady();
  87312. };
  87313. /**
  87314. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  87315. */
  87316. EffectLayer.prototype.render = function () {
  87317. var currentEffect = this._mergeEffect;
  87318. // Check
  87319. if (!currentEffect.isReady())
  87320. return;
  87321. for (var i = 0; i < this._postProcesses.length; i++) {
  87322. if (!this._postProcesses[i].isReady()) {
  87323. return;
  87324. }
  87325. }
  87326. var engine = this._scene.getEngine();
  87327. this.onBeforeComposeObservable.notifyObservers(this);
  87328. // Render
  87329. engine.enableEffect(currentEffect);
  87330. engine.setState(false);
  87331. // VBOs
  87332. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87333. // Cache
  87334. var previousAlphaMode = engine.getAlphaMode();
  87335. // Go Blend.
  87336. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  87337. // Blends the map on the main canvas.
  87338. this._internalRender(currentEffect);
  87339. // Restore Alpha
  87340. engine.setAlphaMode(previousAlphaMode);
  87341. this.onAfterComposeObservable.notifyObservers(this);
  87342. // Handle size changes.
  87343. var size = this._mainTexture.getSize();
  87344. this._setMainTextureSize();
  87345. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  87346. // Recreate RTT and post processes on size change.
  87347. this.onSizeChangedObservable.notifyObservers(this);
  87348. this._disposeTextureAndPostProcesses();
  87349. this._createMainTexture();
  87350. this._createTextureAndPostProcesses();
  87351. }
  87352. };
  87353. /**
  87354. * Determine if a given mesh will be used in the current effect.
  87355. * @param mesh mesh to test
  87356. * @returns true if the mesh will be used
  87357. */
  87358. EffectLayer.prototype.hasMesh = function (mesh) {
  87359. return true;
  87360. };
  87361. /**
  87362. * Returns true if the layer contains information to display, otherwise false.
  87363. * @returns true if the glow layer should be rendered
  87364. */
  87365. EffectLayer.prototype.shouldRender = function () {
  87366. return this.isEnabled && this._shouldRender;
  87367. };
  87368. /**
  87369. * Returns true if the mesh should render, otherwise false.
  87370. * @param mesh The mesh to render
  87371. * @returns true if it should render otherwise false
  87372. */
  87373. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  87374. return true;
  87375. };
  87376. /**
  87377. * Returns true if the mesh should render, otherwise false.
  87378. * @param mesh The mesh to render
  87379. * @returns true if it should render otherwise false
  87380. */
  87381. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  87382. return true;
  87383. };
  87384. /**
  87385. * Renders the submesh passed in parameter to the generation map.
  87386. */
  87387. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  87388. var _this = this;
  87389. if (!this.shouldRender()) {
  87390. return;
  87391. }
  87392. var material = subMesh.getMaterial();
  87393. var mesh = subMesh.getRenderingMesh();
  87394. var scene = this._scene;
  87395. var engine = scene.getEngine();
  87396. if (!material) {
  87397. return;
  87398. }
  87399. // Do not block in blend mode.
  87400. if (material.needAlphaBlendingForMesh(mesh)) {
  87401. return;
  87402. }
  87403. // Culling
  87404. engine.setState(material.backFaceCulling);
  87405. // Managing instances
  87406. var batch = mesh._getInstancesRenderList(subMesh._id);
  87407. if (batch.mustReturn) {
  87408. return;
  87409. }
  87410. // Early Exit per mesh
  87411. if (!this._shouldRenderMesh(mesh)) {
  87412. return;
  87413. }
  87414. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  87415. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  87416. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  87417. engine.enableEffect(this._effectLayerMapGenerationEffect);
  87418. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  87419. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  87420. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  87421. // Alpha test
  87422. if (material && material.needAlphaTesting()) {
  87423. var alphaTexture = material.getAlphaTestTexture();
  87424. if (alphaTexture) {
  87425. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  87426. var textureMatrix = alphaTexture.getTextureMatrix();
  87427. if (textureMatrix) {
  87428. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  87429. }
  87430. }
  87431. }
  87432. // Glow emissive only
  87433. if (this._emissiveTextureAndColor.texture) {
  87434. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  87435. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  87436. }
  87437. // Bones
  87438. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  87439. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  87440. }
  87441. // Morph targets
  87442. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  87443. // Draw
  87444. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  87445. }
  87446. else {
  87447. // Need to reset refresh rate of the shadowMap
  87448. this._mainTexture.resetRefreshCounter();
  87449. }
  87450. };
  87451. /**
  87452. * Rebuild the required buffers.
  87453. * @ignore Internal use only.
  87454. */
  87455. EffectLayer.prototype._rebuild = function () {
  87456. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87457. if (vb) {
  87458. vb._rebuild();
  87459. }
  87460. this._generateIndexBuffer();
  87461. };
  87462. /**
  87463. * Dispose only the render target textures and post process.
  87464. */
  87465. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  87466. this._mainTexture.dispose();
  87467. for (var i = 0; i < this._postProcesses.length; i++) {
  87468. if (this._postProcesses[i]) {
  87469. this._postProcesses[i].dispose();
  87470. }
  87471. }
  87472. this._postProcesses = [];
  87473. for (var i = 0; i < this._textures.length; i++) {
  87474. if (this._textures[i]) {
  87475. this._textures[i].dispose();
  87476. }
  87477. }
  87478. this._textures = [];
  87479. };
  87480. /**
  87481. * Dispose the highlight layer and free resources.
  87482. */
  87483. EffectLayer.prototype.dispose = function () {
  87484. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87485. if (vertexBuffer) {
  87486. vertexBuffer.dispose();
  87487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87488. }
  87489. if (this._indexBuffer) {
  87490. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87491. this._indexBuffer = null;
  87492. }
  87493. // Clean textures and post processes
  87494. this._disposeTextureAndPostProcesses();
  87495. // Remove from scene
  87496. var index = this._scene.effectLayers.indexOf(this, 0);
  87497. if (index > -1) {
  87498. this._scene.effectLayers.splice(index, 1);
  87499. }
  87500. // Callback
  87501. this.onDisposeObservable.notifyObservers(this);
  87502. this.onDisposeObservable.clear();
  87503. this.onBeforeRenderMainTextureObservable.clear();
  87504. this.onBeforeComposeObservable.clear();
  87505. this.onAfterComposeObservable.clear();
  87506. this.onSizeChangedObservable.clear();
  87507. };
  87508. return EffectLayer;
  87509. }());
  87510. BABYLON.EffectLayer = EffectLayer;
  87511. })(BABYLON || (BABYLON = {}));
  87512. //# sourceMappingURL=babylon.effectLayer.js.map
  87513. "use strict";
  87514. var BABYLON;
  87515. (function (BABYLON) {
  87516. /**
  87517. * Special Glow Blur post process only blurring the alpha channel
  87518. * It enforces keeping the most luminous color in the color channel.
  87519. */
  87520. var GlowBlurPostProcess = /** @class */ (function (_super) {
  87521. __extends(GlowBlurPostProcess, _super);
  87522. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  87523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87524. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  87525. _this.direction = direction;
  87526. _this.kernel = kernel;
  87527. _this.onApplyObservable.add(function (effect) {
  87528. effect.setFloat2("screenSize", _this.width, _this.height);
  87529. effect.setVector2("direction", _this.direction);
  87530. effect.setFloat("blurWidth", _this.kernel);
  87531. });
  87532. return _this;
  87533. }
  87534. return GlowBlurPostProcess;
  87535. }(BABYLON.PostProcess));
  87536. /**
  87537. * The highlight layer Helps adding a glow effect around a mesh.
  87538. *
  87539. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87540. * glowy meshes to your scene.
  87541. *
  87542. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  87543. */
  87544. var HighlightLayer = /** @class */ (function (_super) {
  87545. __extends(HighlightLayer, _super);
  87546. /**
  87547. * Instantiates a new highlight Layer and references it to the scene..
  87548. * @param name The name of the layer
  87549. * @param scene The scene to use the layer in
  87550. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  87551. */
  87552. function HighlightLayer(name, scene, options) {
  87553. var _this = _super.call(this, name, scene) || this;
  87554. _this.name = name;
  87555. /**
  87556. * Specifies whether or not the inner glow is ACTIVE in the layer.
  87557. */
  87558. _this.innerGlow = true;
  87559. /**
  87560. * Specifies whether or not the outer glow is ACTIVE in the layer.
  87561. */
  87562. _this.outerGlow = true;
  87563. /**
  87564. * An event triggered when the highlight layer is being blurred.
  87565. */
  87566. _this.onBeforeBlurObservable = new BABYLON.Observable();
  87567. /**
  87568. * An event triggered when the highlight layer has been blurred.
  87569. */
  87570. _this.onAfterBlurObservable = new BABYLON.Observable();
  87571. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  87572. _this._meshes = {};
  87573. _this._excludedMeshes = {};
  87574. _this.neutralColor = HighlightLayer.NeutralColor;
  87575. // Warn on stencil
  87576. if (!_this._engine.isStencilEnable) {
  87577. 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 }");
  87578. }
  87579. // Adapt options
  87580. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87581. // Initialize the layer
  87582. _this._init({
  87583. alphaBlendingMode: _this._options.alphaBlendingMode,
  87584. camera: _this._options.camera,
  87585. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87586. mainTextureRatio: _this._options.mainTextureRatio
  87587. });
  87588. // Do not render as long as no meshes have been added
  87589. _this._shouldRender = false;
  87590. return _this;
  87591. }
  87592. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  87593. /**
  87594. * Gets the horizontal size of the blur.
  87595. */
  87596. get: function () {
  87597. return this._horizontalBlurPostprocess.kernel;
  87598. },
  87599. /**
  87600. * Specifies the horizontal size of the blur.
  87601. */
  87602. set: function (value) {
  87603. this._horizontalBlurPostprocess.kernel = value;
  87604. },
  87605. enumerable: true,
  87606. configurable: true
  87607. });
  87608. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  87609. /**
  87610. * Gets the vertical size of the blur.
  87611. */
  87612. get: function () {
  87613. return this._verticalBlurPostprocess.kernel;
  87614. },
  87615. /**
  87616. * Specifies the vertical size of the blur.
  87617. */
  87618. set: function (value) {
  87619. this._verticalBlurPostprocess.kernel = value;
  87620. },
  87621. enumerable: true,
  87622. configurable: true
  87623. });
  87624. /**
  87625. * Get the effect name of the layer.
  87626. * @return The effect name
  87627. */
  87628. HighlightLayer.prototype.getEffectName = function () {
  87629. return HighlightLayer.EffectName;
  87630. };
  87631. /**
  87632. * Create the merge effect. This is the shader use to blit the information back
  87633. * to the main canvas at the end of the scene rendering.
  87634. */
  87635. HighlightLayer.prototype._createMergeEffect = function () {
  87636. // Effect
  87637. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  87638. };
  87639. /**
  87640. * Creates the render target textures and post processes used in the highlight layer.
  87641. */
  87642. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  87643. var _this = this;
  87644. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  87645. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  87646. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87647. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87648. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  87649. width: blurTextureWidth,
  87650. height: blurTextureHeight
  87651. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87652. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87653. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87654. this._blurTexture.anisotropicFilteringLevel = 16;
  87655. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87656. this._blurTexture.renderParticles = false;
  87657. this._blurTexture.ignoreCameraViewport = true;
  87658. this._textures = [this._blurTexture];
  87659. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  87660. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87661. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  87662. effect.setTexture("textureSampler", _this._mainTexture);
  87663. });
  87664. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87665. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87666. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87667. });
  87668. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87669. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  87670. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87671. });
  87672. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87673. }
  87674. else {
  87675. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  87676. width: blurTextureWidth,
  87677. height: blurTextureHeight
  87678. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87679. this._horizontalBlurPostprocess.width = blurTextureWidth;
  87680. this._horizontalBlurPostprocess.height = blurTextureHeight;
  87681. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87682. effect.setTexture("textureSampler", _this._mainTexture);
  87683. });
  87684. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  87685. width: blurTextureWidth,
  87686. height: blurTextureHeight
  87687. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87688. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87689. }
  87690. this._mainTexture.onAfterUnbindObservable.add(function () {
  87691. _this.onBeforeBlurObservable.notifyObservers(_this);
  87692. var internalTexture = _this._blurTexture.getInternalTexture();
  87693. if (internalTexture) {
  87694. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  87695. }
  87696. _this.onAfterBlurObservable.notifyObservers(_this);
  87697. });
  87698. // Prevent autoClear.
  87699. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87700. };
  87701. /**
  87702. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87703. */
  87704. HighlightLayer.prototype.needStencil = function () {
  87705. return true;
  87706. };
  87707. /**
  87708. * Checks for the readiness of the element composing the layer.
  87709. * @param subMesh the mesh to check for
  87710. * @param useInstances specify wether or not to use instances to render the mesh
  87711. * @param emissiveTexture the associated emissive texture used to generate the glow
  87712. * @return true if ready otherwise, false
  87713. */
  87714. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  87715. var material = subMesh.getMaterial();
  87716. var mesh = subMesh.getRenderingMesh();
  87717. if (!material || !mesh || !this._meshes) {
  87718. return false;
  87719. }
  87720. var emissiveTexture = null;
  87721. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87722. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87723. emissiveTexture = material.emissiveTexture;
  87724. }
  87725. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87726. };
  87727. /**
  87728. * Implementation specific of rendering the generating effect on the main canvas.
  87729. * @param effect The effect used to render through
  87730. */
  87731. HighlightLayer.prototype._internalRender = function (effect) {
  87732. // Texture
  87733. effect.setTexture("textureSampler", this._blurTexture);
  87734. // Cache
  87735. var engine = this._engine;
  87736. var previousStencilBuffer = engine.getStencilBuffer();
  87737. var previousStencilFunction = engine.getStencilFunction();
  87738. var previousStencilMask = engine.getStencilMask();
  87739. var previousStencilOperationPass = engine.getStencilOperationPass();
  87740. var previousStencilOperationFail = engine.getStencilOperationFail();
  87741. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87742. var previousStencilReference = engine.getStencilFunctionReference();
  87743. // Stencil operations
  87744. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87745. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87746. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87747. // Draw order
  87748. engine.setStencilMask(0x00);
  87749. engine.setStencilBuffer(true);
  87750. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87751. // 2 passes inner outer
  87752. if (this.outerGlow) {
  87753. effect.setFloat("offset", 0);
  87754. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87755. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87756. }
  87757. if (this.innerGlow) {
  87758. effect.setFloat("offset", 1);
  87759. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87760. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87761. }
  87762. // Restore Cache
  87763. engine.setStencilFunction(previousStencilFunction);
  87764. engine.setStencilMask(previousStencilMask);
  87765. engine.setStencilBuffer(previousStencilBuffer);
  87766. engine.setStencilOperationPass(previousStencilOperationPass);
  87767. engine.setStencilOperationFail(previousStencilOperationFail);
  87768. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87769. engine.setStencilFunctionReference(previousStencilReference);
  87770. };
  87771. /**
  87772. * Returns true if the layer contains information to display, otherwise false.
  87773. */
  87774. HighlightLayer.prototype.shouldRender = function () {
  87775. if (_super.prototype.shouldRender.call(this)) {
  87776. return this._meshes ? true : false;
  87777. }
  87778. return false;
  87779. };
  87780. /**
  87781. * Returns true if the mesh should render, otherwise false.
  87782. * @param mesh The mesh to render
  87783. * @returns true if it should render otherwise false
  87784. */
  87785. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87786. // Excluded Mesh
  87787. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87788. return false;
  87789. }
  87790. ;
  87791. return true;
  87792. };
  87793. /**
  87794. * Sets the required values for both the emissive texture and and the main color.
  87795. */
  87796. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87797. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87798. if (highlightLayerMesh) {
  87799. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87800. }
  87801. else {
  87802. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87803. }
  87804. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87805. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87806. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87807. }
  87808. else {
  87809. this._emissiveTextureAndColor.texture = null;
  87810. }
  87811. };
  87812. /**
  87813. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87814. * @param mesh The mesh to exclude from the highlight layer
  87815. */
  87816. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87817. if (!this._excludedMeshes) {
  87818. return;
  87819. }
  87820. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87821. if (!meshExcluded) {
  87822. this._excludedMeshes[mesh.uniqueId] = {
  87823. mesh: mesh,
  87824. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87825. mesh.getEngine().setStencilBuffer(false);
  87826. }),
  87827. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87828. mesh.getEngine().setStencilBuffer(true);
  87829. }),
  87830. };
  87831. }
  87832. };
  87833. /**
  87834. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87835. * @param mesh The mesh to highlight
  87836. */
  87837. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87838. if (!this._excludedMeshes) {
  87839. return;
  87840. }
  87841. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87842. if (meshExcluded) {
  87843. if (meshExcluded.beforeRender) {
  87844. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87845. }
  87846. if (meshExcluded.afterRender) {
  87847. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87848. }
  87849. }
  87850. this._excludedMeshes[mesh.uniqueId] = null;
  87851. };
  87852. /**
  87853. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87854. * @param mesh mesh to test
  87855. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87856. */
  87857. HighlightLayer.prototype.hasMesh = function (mesh) {
  87858. if (!this._meshes) {
  87859. return false;
  87860. }
  87861. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87862. };
  87863. /**
  87864. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87865. * @param mesh The mesh to highlight
  87866. * @param color The color of the highlight
  87867. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87868. */
  87869. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87870. var _this = this;
  87871. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87872. if (!this._meshes) {
  87873. return;
  87874. }
  87875. var meshHighlight = this._meshes[mesh.uniqueId];
  87876. if (meshHighlight) {
  87877. meshHighlight.color = color;
  87878. }
  87879. else {
  87880. this._meshes[mesh.uniqueId] = {
  87881. mesh: mesh,
  87882. color: color,
  87883. // Lambda required for capture due to Observable this context
  87884. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87885. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87886. _this._defaultStencilReference(mesh);
  87887. }
  87888. else {
  87889. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87890. }
  87891. }),
  87892. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87893. glowEmissiveOnly: glowEmissiveOnly
  87894. };
  87895. }
  87896. this._shouldRender = true;
  87897. };
  87898. /**
  87899. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87900. * @param mesh The mesh to highlight
  87901. */
  87902. HighlightLayer.prototype.removeMesh = function (mesh) {
  87903. if (!this._meshes) {
  87904. return;
  87905. }
  87906. var meshHighlight = this._meshes[mesh.uniqueId];
  87907. if (meshHighlight) {
  87908. if (meshHighlight.observerHighlight) {
  87909. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87910. }
  87911. if (meshHighlight.observerDefault) {
  87912. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87913. }
  87914. delete this._meshes[mesh.uniqueId];
  87915. }
  87916. this._shouldRender = false;
  87917. for (var meshHighlightToCheck in this._meshes) {
  87918. if (this._meshes[meshHighlightToCheck]) {
  87919. this._shouldRender = true;
  87920. break;
  87921. }
  87922. }
  87923. };
  87924. /**
  87925. * Force the stencil to the normal expected value for none glowing parts
  87926. */
  87927. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87928. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87929. };
  87930. /**
  87931. * Free any resources and references associated to a mesh.
  87932. * Internal use
  87933. * @param mesh The mesh to free.
  87934. */
  87935. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87936. this.removeMesh(mesh);
  87937. this.removeExcludedMesh(mesh);
  87938. };
  87939. /**
  87940. * Dispose the highlight layer and free resources.
  87941. */
  87942. HighlightLayer.prototype.dispose = function () {
  87943. if (this._meshes) {
  87944. // Clean mesh references
  87945. for (var id in this._meshes) {
  87946. var meshHighlight = this._meshes[id];
  87947. if (meshHighlight && meshHighlight.mesh) {
  87948. if (meshHighlight.observerHighlight) {
  87949. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87950. }
  87951. if (meshHighlight.observerDefault) {
  87952. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87953. }
  87954. }
  87955. }
  87956. this._meshes = null;
  87957. }
  87958. if (this._excludedMeshes) {
  87959. for (var id in this._excludedMeshes) {
  87960. var meshHighlight = this._excludedMeshes[id];
  87961. if (meshHighlight) {
  87962. if (meshHighlight.beforeRender) {
  87963. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87964. }
  87965. if (meshHighlight.afterRender) {
  87966. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87967. }
  87968. }
  87969. }
  87970. this._excludedMeshes = null;
  87971. }
  87972. _super.prototype.dispose.call(this);
  87973. };
  87974. /**
  87975. * Effect Name of the highlight layer.
  87976. */
  87977. HighlightLayer.EffectName = "HighlightLayer";
  87978. /**
  87979. * The neutral color used during the preparation of the glow effect.
  87980. * This is black by default as the blend operation is a blend operation.
  87981. */
  87982. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87983. /**
  87984. * Stencil value used for glowing meshes.
  87985. */
  87986. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87987. /**
  87988. * Stencil value used for the other meshes in the scene.
  87989. */
  87990. HighlightLayer.NormalMeshStencilReference = 0x01;
  87991. return HighlightLayer;
  87992. }(BABYLON.EffectLayer));
  87993. BABYLON.HighlightLayer = HighlightLayer;
  87994. })(BABYLON || (BABYLON = {}));
  87995. //# sourceMappingURL=babylon.highlightLayer.js.map
  87996. "use strict";
  87997. var BABYLON;
  87998. (function (BABYLON) {
  87999. /**
  88000. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  88001. *
  88002. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  88003. * glowy meshes to your scene.
  88004. *
  88005. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  88006. */
  88007. var GlowLayer = /** @class */ (function (_super) {
  88008. __extends(GlowLayer, _super);
  88009. /**
  88010. * Instantiates a new glow Layer and references it to the scene.
  88011. * @param name The name of the layer
  88012. * @param scene The scene to use the layer in
  88013. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  88014. */
  88015. function GlowLayer(name, scene, options) {
  88016. var _this = _super.call(this, name, scene) || this;
  88017. _this.name = name;
  88018. _this._intensity = 1.0;
  88019. _this._includedOnlyMeshes = [];
  88020. _this._excludedMeshes = [];
  88021. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  88022. // Adapt options
  88023. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  88024. // Initialize the layer
  88025. _this._init({
  88026. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  88027. camera: _this._options.camera,
  88028. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  88029. mainTextureRatio: _this._options.mainTextureRatio
  88030. });
  88031. return _this;
  88032. }
  88033. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  88034. /**
  88035. * Gets the kernel size of the blur.
  88036. */
  88037. get: function () {
  88038. return this._horizontalBlurPostprocess1.kernel;
  88039. },
  88040. /**
  88041. * Sets the kernel size of the blur.
  88042. */
  88043. set: function (value) {
  88044. this._horizontalBlurPostprocess1.kernel = value;
  88045. this._verticalBlurPostprocess1.kernel = value;
  88046. this._horizontalBlurPostprocess2.kernel = value;
  88047. this._verticalBlurPostprocess2.kernel = value;
  88048. },
  88049. enumerable: true,
  88050. configurable: true
  88051. });
  88052. Object.defineProperty(GlowLayer.prototype, "intensity", {
  88053. /**
  88054. * Gets the glow intensity.
  88055. */
  88056. get: function () {
  88057. return this._intensity;
  88058. },
  88059. /**
  88060. * Sets the glow intensity.
  88061. */
  88062. set: function (value) {
  88063. this._intensity = value;
  88064. },
  88065. enumerable: true,
  88066. configurable: true
  88067. });
  88068. /**
  88069. * Get the effect name of the layer.
  88070. * @return The effect name
  88071. */
  88072. GlowLayer.prototype.getEffectName = function () {
  88073. return GlowLayer.EffectName;
  88074. };
  88075. /**
  88076. * Create the merge effect. This is the shader use to blit the information back
  88077. * to the main canvas at the end of the scene rendering.
  88078. */
  88079. GlowLayer.prototype._createMergeEffect = function () {
  88080. // Effect
  88081. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  88082. };
  88083. /**
  88084. * Creates the render target textures and post processes used in the glow layer.
  88085. */
  88086. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  88087. var _this = this;
  88088. var blurTextureWidth = this._mainTextureDesiredSize.width;
  88089. var blurTextureHeight = this._mainTextureDesiredSize.height;
  88090. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  88091. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  88092. var textureType = 0;
  88093. if (this._engine.getCaps().textureHalfFloatRender) {
  88094. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88095. }
  88096. else {
  88097. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88098. }
  88099. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  88100. width: blurTextureWidth,
  88101. height: blurTextureHeight
  88102. }, this._scene, false, true, textureType);
  88103. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88104. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88105. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88106. this._blurTexture1.renderParticles = false;
  88107. this._blurTexture1.ignoreCameraViewport = true;
  88108. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  88109. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  88110. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  88111. width: blurTextureWidth2,
  88112. height: blurTextureHeight2
  88113. }, this._scene, false, true, textureType);
  88114. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88115. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88116. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88117. this._blurTexture2.renderParticles = false;
  88118. this._blurTexture2.ignoreCameraViewport = true;
  88119. this._textures = [this._blurTexture1, this._blurTexture2];
  88120. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  88121. width: blurTextureWidth,
  88122. height: blurTextureHeight
  88123. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  88124. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  88125. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  88126. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  88127. effect.setTexture("textureSampler", _this._mainTexture);
  88128. });
  88129. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  88130. width: blurTextureWidth,
  88131. height: blurTextureHeight
  88132. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  88133. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  88134. width: blurTextureWidth2,
  88135. height: blurTextureHeight2
  88136. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  88137. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  88138. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  88139. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  88140. effect.setTexture("textureSampler", _this._blurTexture1);
  88141. });
  88142. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  88143. width: blurTextureWidth2,
  88144. height: blurTextureHeight2
  88145. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  88146. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  88147. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  88148. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  88149. this._mainTexture.samples = this._options.mainTextureSamples;
  88150. this._mainTexture.onAfterUnbindObservable.add(function () {
  88151. var internalTexture = _this._blurTexture1.getInternalTexture();
  88152. if (internalTexture) {
  88153. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  88154. internalTexture = _this._blurTexture2.getInternalTexture();
  88155. if (internalTexture) {
  88156. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  88157. }
  88158. }
  88159. });
  88160. // Prevent autoClear.
  88161. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  88162. };
  88163. /**
  88164. * Checks for the readiness of the element composing the layer.
  88165. * @param subMesh the mesh to check for
  88166. * @param useInstances specify wether or not to use instances to render the mesh
  88167. * @param emissiveTexture the associated emissive texture used to generate the glow
  88168. * @return true if ready otherwise, false
  88169. */
  88170. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  88171. var material = subMesh.getMaterial();
  88172. var mesh = subMesh.getRenderingMesh();
  88173. if (!material || !mesh) {
  88174. return false;
  88175. }
  88176. var emissiveTexture = material.emissiveTexture;
  88177. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  88178. };
  88179. /**
  88180. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  88181. */
  88182. GlowLayer.prototype.needStencil = function () {
  88183. return false;
  88184. };
  88185. /**
  88186. * Implementation specific of rendering the generating effect on the main canvas.
  88187. * @param effect The effect used to render through
  88188. */
  88189. GlowLayer.prototype._internalRender = function (effect) {
  88190. // Texture
  88191. effect.setTexture("textureSampler", this._blurTexture1);
  88192. effect.setTexture("textureSampler2", this._blurTexture2);
  88193. effect.setFloat("offset", this._intensity);
  88194. // Cache
  88195. var engine = this._engine;
  88196. var previousStencilBuffer = engine.getStencilBuffer();
  88197. // Draw order
  88198. engine.setStencilBuffer(false);
  88199. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88200. // Draw order
  88201. engine.setStencilBuffer(previousStencilBuffer);
  88202. };
  88203. /**
  88204. * Sets the required values for both the emissive texture and and the main color.
  88205. */
  88206. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  88207. var textureLevel = 1.0;
  88208. if (this.customEmissiveTextureSelector) {
  88209. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  88210. }
  88211. else {
  88212. if (material) {
  88213. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  88214. if (this._emissiveTextureAndColor.texture) {
  88215. textureLevel = this._emissiveTextureAndColor.texture.level;
  88216. }
  88217. }
  88218. else {
  88219. this._emissiveTextureAndColor.texture = null;
  88220. }
  88221. }
  88222. if (this.customEmissiveColorSelector) {
  88223. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  88224. }
  88225. else {
  88226. if (material.emissiveColor) {
  88227. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  88228. }
  88229. else {
  88230. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  88231. }
  88232. }
  88233. };
  88234. /**
  88235. * Returns true if the mesh should render, otherwise false.
  88236. * @param mesh The mesh to render
  88237. * @returns true if it should render otherwise false
  88238. */
  88239. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  88240. return this.hasMesh(mesh);
  88241. };
  88242. /**
  88243. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  88244. * @param mesh The mesh to exclude from the glow layer
  88245. */
  88246. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  88247. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  88248. this._excludedMeshes.push(mesh.uniqueId);
  88249. }
  88250. };
  88251. /**
  88252. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  88253. * @param mesh The mesh to remove
  88254. */
  88255. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  88256. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  88257. if (index !== -1) {
  88258. this._excludedMeshes.splice(index, 1);
  88259. }
  88260. };
  88261. /**
  88262. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  88263. * @param mesh The mesh to include in the glow layer
  88264. */
  88265. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  88266. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  88267. this._includedOnlyMeshes.push(mesh.uniqueId);
  88268. }
  88269. };
  88270. /**
  88271. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  88272. * @param mesh The mesh to remove
  88273. */
  88274. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  88275. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  88276. if (index !== -1) {
  88277. this._includedOnlyMeshes.splice(index, 1);
  88278. }
  88279. };
  88280. /**
  88281. * Determine if a given mesh will be used in the glow layer
  88282. * @param mesh The mesh to test
  88283. * @returns true if the mesh will be highlighted by the current glow layer
  88284. */
  88285. GlowLayer.prototype.hasMesh = function (mesh) {
  88286. // Included Mesh
  88287. if (this._includedOnlyMeshes.length) {
  88288. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  88289. }
  88290. ;
  88291. // Excluded Mesh
  88292. if (this._excludedMeshes.length) {
  88293. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  88294. }
  88295. ;
  88296. return true;
  88297. };
  88298. /**
  88299. * Free any resources and references associated to a mesh.
  88300. * Internal use
  88301. * @param mesh The mesh to free.
  88302. */
  88303. GlowLayer.prototype._disposeMesh = function (mesh) {
  88304. this.removeIncludedOnlyMesh(mesh);
  88305. this.removeExcludedMesh(mesh);
  88306. };
  88307. /**
  88308. * Effect Name of the layer.
  88309. */
  88310. GlowLayer.EffectName = "GlowLayer";
  88311. /**
  88312. * The default blur kernel size used for the glow.
  88313. */
  88314. GlowLayer.DefaultBlurKernelSize = 32;
  88315. /**
  88316. * The default texture size ratio used for the glow.
  88317. */
  88318. GlowLayer.DefaultTextureRatio = 0.5;
  88319. return GlowLayer;
  88320. }(BABYLON.EffectLayer));
  88321. BABYLON.GlowLayer = GlowLayer;
  88322. })(BABYLON || (BABYLON = {}));
  88323. //# sourceMappingURL=babylon.glowLayer.js.map
  88324. "use strict";
  88325. var BABYLON;
  88326. (function (BABYLON) {
  88327. /**
  88328. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  88329. */
  88330. var AssetTaskState;
  88331. (function (AssetTaskState) {
  88332. /**
  88333. * Initialization
  88334. */
  88335. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  88336. /**
  88337. * Running
  88338. */
  88339. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  88340. /**
  88341. * Done
  88342. */
  88343. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  88344. /**
  88345. * Error
  88346. */
  88347. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  88348. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  88349. /**
  88350. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  88351. */
  88352. var AbstractAssetTask = /** @class */ (function () {
  88353. /**
  88354. * Creates a new {BABYLON.AssetsManager}
  88355. * @param name defines the name of the task
  88356. */
  88357. function AbstractAssetTask(
  88358. /**
  88359. * Task name
  88360. */ name) {
  88361. this.name = name;
  88362. this._isCompleted = false;
  88363. this._taskState = AssetTaskState.INIT;
  88364. }
  88365. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  88366. /**
  88367. * Get if the task is completed
  88368. */
  88369. get: function () {
  88370. return this._isCompleted;
  88371. },
  88372. enumerable: true,
  88373. configurable: true
  88374. });
  88375. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  88376. /**
  88377. * Gets the current state of the task
  88378. */
  88379. get: function () {
  88380. return this._taskState;
  88381. },
  88382. enumerable: true,
  88383. configurable: true
  88384. });
  88385. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  88386. /**
  88387. * Gets the current error object (if task is in error)
  88388. */
  88389. get: function () {
  88390. return this._errorObject;
  88391. },
  88392. enumerable: true,
  88393. configurable: true
  88394. });
  88395. /**
  88396. * Internal only
  88397. * @ignore
  88398. */
  88399. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  88400. if (this._errorObject) {
  88401. return;
  88402. }
  88403. this._errorObject = {
  88404. message: message,
  88405. exception: exception
  88406. };
  88407. };
  88408. /**
  88409. * Execute the current task
  88410. * @param scene defines the scene where you want your assets to be loaded
  88411. * @param onSuccess is a callback called when the task is successfully executed
  88412. * @param onError is a callback called if an error occurs
  88413. */
  88414. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88415. var _this = this;
  88416. this._taskState = AssetTaskState.RUNNING;
  88417. this.runTask(scene, function () {
  88418. _this.onDoneCallback(onSuccess, onError);
  88419. }, function (msg, exception) {
  88420. _this.onErrorCallback(onError, msg, exception);
  88421. });
  88422. };
  88423. /**
  88424. * Execute the current task
  88425. * @param scene defines the scene where you want your assets to be loaded
  88426. * @param onSuccess is a callback called when the task is successfully executed
  88427. * @param onError is a callback called if an error occurs
  88428. */
  88429. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88430. throw new Error("runTask is not implemented");
  88431. };
  88432. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  88433. this._taskState = AssetTaskState.ERROR;
  88434. this._errorObject = {
  88435. message: message,
  88436. exception: exception
  88437. };
  88438. if (this.onError) {
  88439. this.onError(this, message, exception);
  88440. }
  88441. onError();
  88442. };
  88443. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  88444. try {
  88445. this._taskState = AssetTaskState.DONE;
  88446. this._isCompleted = true;
  88447. if (this.onSuccess) {
  88448. this.onSuccess(this);
  88449. }
  88450. onSuccess();
  88451. }
  88452. catch (e) {
  88453. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  88454. }
  88455. };
  88456. return AbstractAssetTask;
  88457. }());
  88458. BABYLON.AbstractAssetTask = AbstractAssetTask;
  88459. /**
  88460. * Class used to share progress information about assets loading
  88461. */
  88462. var AssetsProgressEvent = /** @class */ (function () {
  88463. /**
  88464. * Creates a {BABYLON.AssetsProgressEvent}
  88465. * @param remainingCount defines the number of remaining tasks to process
  88466. * @param totalCount defines the total number of tasks
  88467. * @param task defines the task that was just processed
  88468. */
  88469. function AssetsProgressEvent(remainingCount, totalCount, task) {
  88470. this.remainingCount = remainingCount;
  88471. this.totalCount = totalCount;
  88472. this.task = task;
  88473. }
  88474. return AssetsProgressEvent;
  88475. }());
  88476. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  88477. /**
  88478. * Define a task used by {BABYLON.AssetsManager} to load meshes
  88479. */
  88480. var MeshAssetTask = /** @class */ (function (_super) {
  88481. __extends(MeshAssetTask, _super);
  88482. /**
  88483. * Creates a new {BABYLON.MeshAssetTask}
  88484. * @param name defines the name of the task
  88485. * @param meshesNames defines the list of mesh's names you want to load
  88486. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  88487. * @param sceneFilename defines the filename of the scene to load from
  88488. */
  88489. function MeshAssetTask(
  88490. /**
  88491. * Defines the name of the task
  88492. */
  88493. name,
  88494. /**
  88495. * Defines the list of mesh's names you want to load
  88496. */
  88497. meshesNames,
  88498. /**
  88499. * Defines the root url to use as a base to load your meshes and associated resources
  88500. */
  88501. rootUrl,
  88502. /**
  88503. * Defines the filename of the scene to load from
  88504. */
  88505. sceneFilename) {
  88506. var _this = _super.call(this, name) || this;
  88507. _this.name = name;
  88508. _this.meshesNames = meshesNames;
  88509. _this.rootUrl = rootUrl;
  88510. _this.sceneFilename = sceneFilename;
  88511. return _this;
  88512. }
  88513. /**
  88514. * Execute the current task
  88515. * @param scene defines the scene where you want your assets to be loaded
  88516. * @param onSuccess is a callback called when the task is successfully executed
  88517. * @param onError is a callback called if an error occurs
  88518. */
  88519. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88520. var _this = this;
  88521. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  88522. _this.loadedMeshes = meshes;
  88523. _this.loadedParticleSystems = particleSystems;
  88524. _this.loadedSkeletons = skeletons;
  88525. onSuccess();
  88526. }, null, function (scene, message, exception) {
  88527. onError(message, exception);
  88528. });
  88529. };
  88530. return MeshAssetTask;
  88531. }(AbstractAssetTask));
  88532. BABYLON.MeshAssetTask = MeshAssetTask;
  88533. /**
  88534. * Define a task used by {BABYLON.AssetsManager} to load text content
  88535. */
  88536. var TextFileAssetTask = /** @class */ (function (_super) {
  88537. __extends(TextFileAssetTask, _super);
  88538. /**
  88539. * Creates a new TextFileAssetTask object
  88540. * @param name defines the name of the task
  88541. * @param url defines the location of the file to load
  88542. */
  88543. function TextFileAssetTask(
  88544. /**
  88545. * Defines the name of the task
  88546. */
  88547. name,
  88548. /**
  88549. * Defines the location of the file to load
  88550. */
  88551. url) {
  88552. var _this = _super.call(this, name) || this;
  88553. _this.name = name;
  88554. _this.url = url;
  88555. return _this;
  88556. }
  88557. /**
  88558. * Execute the current task
  88559. * @param scene defines the scene where you want your assets to be loaded
  88560. * @param onSuccess is a callback called when the task is successfully executed
  88561. * @param onError is a callback called if an error occurs
  88562. */
  88563. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88564. var _this = this;
  88565. scene._loadFile(this.url, function (data) {
  88566. _this.text = data;
  88567. onSuccess();
  88568. }, undefined, false, false, function (request, exception) {
  88569. if (request) {
  88570. onError(request.status + " " + request.statusText, exception);
  88571. }
  88572. });
  88573. };
  88574. return TextFileAssetTask;
  88575. }(AbstractAssetTask));
  88576. BABYLON.TextFileAssetTask = TextFileAssetTask;
  88577. /**
  88578. * Define a task used by {BABYLON.AssetsManager} to load binary data
  88579. */
  88580. var BinaryFileAssetTask = /** @class */ (function (_super) {
  88581. __extends(BinaryFileAssetTask, _super);
  88582. /**
  88583. * Creates a new BinaryFileAssetTask object
  88584. * @param name defines the name of the new task
  88585. * @param url defines the location of the file to load
  88586. */
  88587. function BinaryFileAssetTask(
  88588. /**
  88589. * Defines the name of the task
  88590. */
  88591. name,
  88592. /**
  88593. * Defines the location of the file to load
  88594. */
  88595. url) {
  88596. var _this = _super.call(this, name) || this;
  88597. _this.name = name;
  88598. _this.url = url;
  88599. return _this;
  88600. }
  88601. /**
  88602. * Execute the current task
  88603. * @param scene defines the scene where you want your assets to be loaded
  88604. * @param onSuccess is a callback called when the task is successfully executed
  88605. * @param onError is a callback called if an error occurs
  88606. */
  88607. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88608. var _this = this;
  88609. scene._loadFile(this.url, function (data) {
  88610. _this.data = data;
  88611. onSuccess();
  88612. }, undefined, true, true, function (request, exception) {
  88613. if (request) {
  88614. onError(request.status + " " + request.statusText, exception);
  88615. }
  88616. });
  88617. };
  88618. return BinaryFileAssetTask;
  88619. }(AbstractAssetTask));
  88620. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  88621. /**
  88622. * Define a task used by {BABYLON.AssetsManager} to load images
  88623. */
  88624. var ImageAssetTask = /** @class */ (function (_super) {
  88625. __extends(ImageAssetTask, _super);
  88626. /**
  88627. * Creates a new ImageAssetTask
  88628. * @param name defines the name of the task
  88629. * @param url defines the location of the image to load
  88630. */
  88631. function ImageAssetTask(
  88632. /**
  88633. * Defines the name of the task
  88634. */
  88635. name,
  88636. /**
  88637. * Defines the location of the image to load
  88638. */
  88639. url) {
  88640. var _this = _super.call(this, name) || this;
  88641. _this.name = name;
  88642. _this.url = url;
  88643. return _this;
  88644. }
  88645. /**
  88646. * Execute the current task
  88647. * @param scene defines the scene where you want your assets to be loaded
  88648. * @param onSuccess is a callback called when the task is successfully executed
  88649. * @param onError is a callback called if an error occurs
  88650. */
  88651. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88652. var _this = this;
  88653. var img = new Image();
  88654. BABYLON.Tools.SetCorsBehavior(this.url, img);
  88655. img.onload = function () {
  88656. _this.image = img;
  88657. onSuccess();
  88658. };
  88659. img.onerror = function (err) {
  88660. onError("Error loading image", err);
  88661. };
  88662. img.src = this.url;
  88663. };
  88664. return ImageAssetTask;
  88665. }(AbstractAssetTask));
  88666. BABYLON.ImageAssetTask = ImageAssetTask;
  88667. /**
  88668. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  88669. */
  88670. var TextureAssetTask = /** @class */ (function (_super) {
  88671. __extends(TextureAssetTask, _super);
  88672. /**
  88673. * Creates a new TextureAssetTask object
  88674. * @param name defines the name of the task
  88675. * @param url defines the location of the file to load
  88676. * @param noMipmap defines if mipmap should not be generated (default is false)
  88677. * @param invertY defines if texture must be inverted on Y axis (default is false)
  88678. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88679. */
  88680. function TextureAssetTask(
  88681. /**
  88682. * Defines the name of the task
  88683. */
  88684. name,
  88685. /**
  88686. * Defines the location of the file to load
  88687. */
  88688. url,
  88689. /**
  88690. * Defines if mipmap should not be generated (default is false)
  88691. */
  88692. noMipmap,
  88693. /**
  88694. * Defines if texture must be inverted on Y axis (default is false)
  88695. */
  88696. invertY,
  88697. /**
  88698. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88699. */
  88700. samplingMode) {
  88701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88702. var _this = _super.call(this, name) || this;
  88703. _this.name = name;
  88704. _this.url = url;
  88705. _this.noMipmap = noMipmap;
  88706. _this.invertY = invertY;
  88707. _this.samplingMode = samplingMode;
  88708. return _this;
  88709. }
  88710. /**
  88711. * Execute the current task
  88712. * @param scene defines the scene where you want your assets to be loaded
  88713. * @param onSuccess is a callback called when the task is successfully executed
  88714. * @param onError is a callback called if an error occurs
  88715. */
  88716. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88717. var onload = function () {
  88718. onSuccess();
  88719. };
  88720. var onerror = function (message, exception) {
  88721. onError(message, exception);
  88722. };
  88723. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  88724. };
  88725. return TextureAssetTask;
  88726. }(AbstractAssetTask));
  88727. BABYLON.TextureAssetTask = TextureAssetTask;
  88728. /**
  88729. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  88730. */
  88731. var CubeTextureAssetTask = /** @class */ (function (_super) {
  88732. __extends(CubeTextureAssetTask, _super);
  88733. /**
  88734. * Creates a new CubeTextureAssetTask
  88735. * @param name defines the name of the task
  88736. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88737. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88738. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88739. * @param files defines the explicit list of files (undefined by default)
  88740. */
  88741. function CubeTextureAssetTask(
  88742. /**
  88743. * Defines the name of the task
  88744. */
  88745. name,
  88746. /**
  88747. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88748. */
  88749. url,
  88750. /**
  88751. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88752. */
  88753. extensions,
  88754. /**
  88755. * Defines if mipmaps should not be generated (default is false)
  88756. */
  88757. noMipmap,
  88758. /**
  88759. * Defines the explicit list of files (undefined by default)
  88760. */
  88761. files) {
  88762. var _this = _super.call(this, name) || this;
  88763. _this.name = name;
  88764. _this.url = url;
  88765. _this.extensions = extensions;
  88766. _this.noMipmap = noMipmap;
  88767. _this.files = files;
  88768. return _this;
  88769. }
  88770. /**
  88771. * Execute the current task
  88772. * @param scene defines the scene where you want your assets to be loaded
  88773. * @param onSuccess is a callback called when the task is successfully executed
  88774. * @param onError is a callback called if an error occurs
  88775. */
  88776. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88777. var onload = function () {
  88778. onSuccess();
  88779. };
  88780. var onerror = function (message, exception) {
  88781. onError(message, exception);
  88782. };
  88783. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88784. };
  88785. return CubeTextureAssetTask;
  88786. }(AbstractAssetTask));
  88787. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88788. /**
  88789. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88790. */
  88791. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88792. __extends(HDRCubeTextureAssetTask, _super);
  88793. /**
  88794. * Creates a new HDRCubeTextureAssetTask object
  88795. * @param name defines the name of the task
  88796. * @param url defines the location of the file to load
  88797. * @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.
  88798. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88799. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88800. * @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)
  88801. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88802. */
  88803. function HDRCubeTextureAssetTask(
  88804. /**
  88805. * Defines the name of the task
  88806. */
  88807. name,
  88808. /**
  88809. * Defines the location of the file to load
  88810. */
  88811. url,
  88812. /**
  88813. * 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.
  88814. */
  88815. size,
  88816. /**
  88817. * Defines if mipmaps should not be generated (default is false)
  88818. */
  88819. noMipmap,
  88820. /**
  88821. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88822. */
  88823. generateHarmonics,
  88824. /**
  88825. * 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)
  88826. */
  88827. useInGammaSpace,
  88828. /**
  88829. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88830. */
  88831. usePMREMGenerator) {
  88832. if (noMipmap === void 0) { noMipmap = false; }
  88833. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88834. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88835. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88836. var _this = _super.call(this, name) || this;
  88837. _this.name = name;
  88838. _this.url = url;
  88839. _this.size = size;
  88840. _this.noMipmap = noMipmap;
  88841. _this.generateHarmonics = generateHarmonics;
  88842. _this.useInGammaSpace = useInGammaSpace;
  88843. _this.usePMREMGenerator = usePMREMGenerator;
  88844. return _this;
  88845. }
  88846. /**
  88847. * Execute the current task
  88848. * @param scene defines the scene where you want your assets to be loaded
  88849. * @param onSuccess is a callback called when the task is successfully executed
  88850. * @param onError is a callback called if an error occurs
  88851. */
  88852. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88853. var onload = function () {
  88854. onSuccess();
  88855. };
  88856. var onerror = function (message, exception) {
  88857. onError(message, exception);
  88858. };
  88859. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88860. };
  88861. return HDRCubeTextureAssetTask;
  88862. }(AbstractAssetTask));
  88863. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88864. /**
  88865. * This class can be used to easily import assets into a scene
  88866. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88867. */
  88868. var AssetsManager = /** @class */ (function () {
  88869. /**
  88870. * Creates a new AssetsManager
  88871. * @param scene defines the scene to work on
  88872. */
  88873. function AssetsManager(scene) {
  88874. this._isLoading = false;
  88875. this._tasks = new Array();
  88876. this._waitingTasksCount = 0;
  88877. this._totalTasksCount = 0;
  88878. /**
  88879. * Observable called when all tasks are processed
  88880. */
  88881. this.onTaskSuccessObservable = new BABYLON.Observable();
  88882. /**
  88883. * Observable called when a task had an error
  88884. */
  88885. this.onTaskErrorObservable = new BABYLON.Observable();
  88886. /**
  88887. * Observable called when a task is successful
  88888. */
  88889. this.onTasksDoneObservable = new BABYLON.Observable();
  88890. /**
  88891. * Observable called when a task is done (whatever the result is)
  88892. */
  88893. this.onProgressObservable = new BABYLON.Observable();
  88894. /**
  88895. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88896. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88897. */
  88898. this.useDefaultLoadingScreen = true;
  88899. this._scene = scene;
  88900. }
  88901. /**
  88902. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88903. * @param taskName defines the name of the new task
  88904. * @param meshesNames defines the name of meshes to load
  88905. * @param rootUrl defines the root url to use to locate files
  88906. * @param sceneFilename defines the filename of the scene file
  88907. * @returns a new {BABYLON.MeshAssetTask} object
  88908. */
  88909. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88910. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88911. this._tasks.push(task);
  88912. return task;
  88913. };
  88914. /**
  88915. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88916. * @param taskName defines the name of the new task
  88917. * @param url defines the url of the file to load
  88918. * @returns a new {BABYLON.TextFileAssetTask} object
  88919. */
  88920. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88921. var task = new TextFileAssetTask(taskName, url);
  88922. this._tasks.push(task);
  88923. return task;
  88924. };
  88925. /**
  88926. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88927. * @param taskName defines the name of the new task
  88928. * @param url defines the url of the file to load
  88929. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88930. */
  88931. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88932. var task = new BinaryFileAssetTask(taskName, url);
  88933. this._tasks.push(task);
  88934. return task;
  88935. };
  88936. /**
  88937. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88938. * @param taskName defines the name of the new task
  88939. * @param url defines the url of the file to load
  88940. * @returns a new {BABYLON.ImageAssetTask} object
  88941. */
  88942. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88943. var task = new ImageAssetTask(taskName, url);
  88944. this._tasks.push(task);
  88945. return task;
  88946. };
  88947. /**
  88948. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88949. * @param taskName defines the name of the new task
  88950. * @param url defines the url of the file to load
  88951. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88952. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88953. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88954. * @returns a new {BABYLON.TextureAssetTask} object
  88955. */
  88956. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88957. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88958. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88959. this._tasks.push(task);
  88960. return task;
  88961. };
  88962. /**
  88963. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88964. * @param taskName defines the name of the new task
  88965. * @param url defines the url of the file to load
  88966. * @param extensions defines the extension to use to load the cube map (can be null)
  88967. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88968. * @param files defines the list of files to load (can be null)
  88969. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88970. */
  88971. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88972. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88973. this._tasks.push(task);
  88974. return task;
  88975. };
  88976. /**
  88977. *
  88978. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88979. * @param taskName defines the name of the new task
  88980. * @param url defines the url of the file to load
  88981. * @param size defines the size you want for the cubemap (can be null)
  88982. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88983. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88984. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88985. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88986. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88987. */
  88988. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88989. if (noMipmap === void 0) { noMipmap = false; }
  88990. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88991. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88992. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88993. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88994. this._tasks.push(task);
  88995. return task;
  88996. };
  88997. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88998. var _this = this;
  88999. this._waitingTasksCount--;
  89000. try {
  89001. if (task.taskState === AssetTaskState.DONE) {
  89002. // Let's remove successfull tasks
  89003. BABYLON.Tools.SetImmediate(function () {
  89004. var index = _this._tasks.indexOf(task);
  89005. if (index > -1) {
  89006. _this._tasks.splice(index, 1);
  89007. }
  89008. });
  89009. }
  89010. if (this.onProgress) {
  89011. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  89012. }
  89013. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  89014. }
  89015. catch (e) {
  89016. BABYLON.Tools.Error("Error running progress callbacks.");
  89017. console.log(e);
  89018. }
  89019. if (this._waitingTasksCount === 0) {
  89020. try {
  89021. if (this.onFinish) {
  89022. this.onFinish(this._tasks);
  89023. }
  89024. this.onTasksDoneObservable.notifyObservers(this._tasks);
  89025. }
  89026. catch (e) {
  89027. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  89028. console.log(e);
  89029. }
  89030. this._isLoading = false;
  89031. this._scene.getEngine().hideLoadingUI();
  89032. }
  89033. };
  89034. AssetsManager.prototype._runTask = function (task) {
  89035. var _this = this;
  89036. var done = function () {
  89037. try {
  89038. if (_this.onTaskSuccess) {
  89039. _this.onTaskSuccess(task);
  89040. }
  89041. _this.onTaskSuccessObservable.notifyObservers(task);
  89042. _this._decreaseWaitingTasksCount(task);
  89043. }
  89044. catch (e) {
  89045. error("Error executing task success callbacks", e);
  89046. }
  89047. };
  89048. var error = function (message, exception) {
  89049. task._setErrorObject(message, exception);
  89050. if (_this.onTaskError) {
  89051. _this.onTaskError(task);
  89052. }
  89053. _this.onTaskErrorObservable.notifyObservers(task);
  89054. _this._decreaseWaitingTasksCount(task);
  89055. };
  89056. task.run(this._scene, done, error);
  89057. };
  89058. /**
  89059. * Reset the {BABYLON.AssetsManager} and remove all tasks
  89060. * @return the current instance of the {BABYLON.AssetsManager}
  89061. */
  89062. AssetsManager.prototype.reset = function () {
  89063. this._isLoading = false;
  89064. this._tasks = new Array();
  89065. return this;
  89066. };
  89067. /**
  89068. * Start the loading process
  89069. * @return the current instance of the {BABYLON.AssetsManager}
  89070. */
  89071. AssetsManager.prototype.load = function () {
  89072. if (this._isLoading) {
  89073. return this;
  89074. }
  89075. this._isLoading = true;
  89076. this._waitingTasksCount = this._tasks.length;
  89077. this._totalTasksCount = this._tasks.length;
  89078. if (this._waitingTasksCount === 0) {
  89079. this._isLoading = false;
  89080. if (this.onFinish) {
  89081. this.onFinish(this._tasks);
  89082. }
  89083. this.onTasksDoneObservable.notifyObservers(this._tasks);
  89084. return this;
  89085. }
  89086. if (this.useDefaultLoadingScreen) {
  89087. this._scene.getEngine().displayLoadingUI();
  89088. }
  89089. for (var index = 0; index < this._tasks.length; index++) {
  89090. var task = this._tasks[index];
  89091. this._runTask(task);
  89092. }
  89093. return this;
  89094. };
  89095. return AssetsManager;
  89096. }());
  89097. BABYLON.AssetsManager = AssetsManager;
  89098. })(BABYLON || (BABYLON = {}));
  89099. //# sourceMappingURL=babylon.assetsManager.js.map
  89100. "use strict";
  89101. var BABYLON;
  89102. (function (BABYLON) {
  89103. var serializedGeometries = [];
  89104. var serializeGeometry = function (geometry, serializationGeometries) {
  89105. if (serializedGeometries[geometry.id]) {
  89106. return;
  89107. }
  89108. if (geometry.doNotSerialize) {
  89109. return;
  89110. }
  89111. if (geometry instanceof BABYLON.BoxGeometry) {
  89112. serializationGeometries.boxes.push(geometry.serialize());
  89113. }
  89114. else if (geometry instanceof BABYLON.SphereGeometry) {
  89115. serializationGeometries.spheres.push(geometry.serialize());
  89116. }
  89117. else if (geometry instanceof BABYLON.CylinderGeometry) {
  89118. serializationGeometries.cylinders.push(geometry.serialize());
  89119. }
  89120. else if (geometry instanceof BABYLON.TorusGeometry) {
  89121. serializationGeometries.toruses.push(geometry.serialize());
  89122. }
  89123. else if (geometry instanceof BABYLON.GroundGeometry) {
  89124. serializationGeometries.grounds.push(geometry.serialize());
  89125. }
  89126. else if (geometry instanceof BABYLON.Plane) {
  89127. serializationGeometries.planes.push(geometry.serialize());
  89128. }
  89129. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  89130. serializationGeometries.torusKnots.push(geometry.serialize());
  89131. }
  89132. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  89133. throw new Error("Unknown primitive type");
  89134. }
  89135. else {
  89136. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  89137. }
  89138. serializedGeometries[geometry.id] = true;
  89139. };
  89140. var serializeMesh = function (mesh, serializationScene) {
  89141. var serializationObject = {};
  89142. // Geometry
  89143. var geometry = mesh._geometry;
  89144. if (geometry) {
  89145. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  89146. // 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
  89147. serializeGeometry(geometry, serializationScene.geometries);
  89148. }
  89149. }
  89150. // Custom
  89151. if (mesh.serialize) {
  89152. mesh.serialize(serializationObject);
  89153. }
  89154. return serializationObject;
  89155. };
  89156. var finalizeSingleMesh = function (mesh, serializationObject) {
  89157. //only works if the mesh is already loaded
  89158. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  89159. //serialize material
  89160. if (mesh.material) {
  89161. if (mesh.material instanceof BABYLON.StandardMaterial) {
  89162. serializationObject.materials = serializationObject.materials || [];
  89163. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  89164. serializationObject.materials.push(mesh.material.serialize());
  89165. }
  89166. }
  89167. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  89168. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  89169. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  89170. serializationObject.multiMaterials.push(mesh.material.serialize());
  89171. }
  89172. }
  89173. }
  89174. //serialize geometry
  89175. var geometry = mesh._geometry;
  89176. if (geometry) {
  89177. if (!serializationObject.geometries) {
  89178. serializationObject.geometries = {};
  89179. serializationObject.geometries.boxes = [];
  89180. serializationObject.geometries.spheres = [];
  89181. serializationObject.geometries.cylinders = [];
  89182. serializationObject.geometries.toruses = [];
  89183. serializationObject.geometries.grounds = [];
  89184. serializationObject.geometries.planes = [];
  89185. serializationObject.geometries.torusKnots = [];
  89186. serializationObject.geometries.vertexData = [];
  89187. }
  89188. serializeGeometry(geometry, serializationObject.geometries);
  89189. }
  89190. // Skeletons
  89191. if (mesh.skeleton) {
  89192. serializationObject.skeletons = serializationObject.skeletons || [];
  89193. serializationObject.skeletons.push(mesh.skeleton.serialize());
  89194. }
  89195. //serialize the actual mesh
  89196. serializationObject.meshes = serializationObject.meshes || [];
  89197. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  89198. }
  89199. };
  89200. var SceneSerializer = /** @class */ (function () {
  89201. function SceneSerializer() {
  89202. }
  89203. SceneSerializer.ClearCache = function () {
  89204. serializedGeometries = [];
  89205. };
  89206. SceneSerializer.Serialize = function (scene) {
  89207. var serializationObject = {};
  89208. SceneSerializer.ClearCache();
  89209. // Scene
  89210. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  89211. serializationObject.autoClear = scene.autoClear;
  89212. serializationObject.clearColor = scene.clearColor.asArray();
  89213. serializationObject.ambientColor = scene.ambientColor.asArray();
  89214. serializationObject.gravity = scene.gravity.asArray();
  89215. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  89216. serializationObject.workerCollisions = scene.workerCollisions;
  89217. // Fog
  89218. if (scene.fogMode && scene.fogMode !== 0) {
  89219. serializationObject.fogMode = scene.fogMode;
  89220. serializationObject.fogColor = scene.fogColor.asArray();
  89221. serializationObject.fogStart = scene.fogStart;
  89222. serializationObject.fogEnd = scene.fogEnd;
  89223. serializationObject.fogDensity = scene.fogDensity;
  89224. }
  89225. //Physics
  89226. if (scene.isPhysicsEnabled()) {
  89227. var physicEngine = scene.getPhysicsEngine();
  89228. if (physicEngine) {
  89229. serializationObject.physicsEnabled = true;
  89230. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  89231. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  89232. }
  89233. }
  89234. // Metadata
  89235. if (scene.metadata) {
  89236. serializationObject.metadata = scene.metadata;
  89237. }
  89238. // Morph targets
  89239. serializationObject.morphTargetManagers = [];
  89240. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  89241. var abstractMesh = _a[_i];
  89242. var manager = abstractMesh.morphTargetManager;
  89243. if (manager) {
  89244. serializationObject.morphTargetManagers.push(manager.serialize());
  89245. }
  89246. }
  89247. // Lights
  89248. serializationObject.lights = [];
  89249. var index;
  89250. var light;
  89251. for (index = 0; index < scene.lights.length; index++) {
  89252. light = scene.lights[index];
  89253. if (!light.doNotSerialize) {
  89254. serializationObject.lights.push(light.serialize());
  89255. }
  89256. }
  89257. // Cameras
  89258. serializationObject.cameras = [];
  89259. for (index = 0; index < scene.cameras.length; index++) {
  89260. var camera = scene.cameras[index];
  89261. if (!camera.doNotSerialize) {
  89262. serializationObject.cameras.push(camera.serialize());
  89263. }
  89264. }
  89265. if (scene.activeCamera) {
  89266. serializationObject.activeCameraID = scene.activeCamera.id;
  89267. }
  89268. // Animations
  89269. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  89270. // Materials
  89271. serializationObject.materials = [];
  89272. serializationObject.multiMaterials = [];
  89273. var material;
  89274. for (index = 0; index < scene.materials.length; index++) {
  89275. material = scene.materials[index];
  89276. if (!material.doNotSerialize) {
  89277. serializationObject.materials.push(material.serialize());
  89278. }
  89279. }
  89280. // MultiMaterials
  89281. serializationObject.multiMaterials = [];
  89282. for (index = 0; index < scene.multiMaterials.length; index++) {
  89283. var multiMaterial = scene.multiMaterials[index];
  89284. serializationObject.multiMaterials.push(multiMaterial.serialize());
  89285. }
  89286. // Environment texture
  89287. if (scene.environmentTexture) {
  89288. serializationObject.environmentTexture = scene.environmentTexture.name;
  89289. }
  89290. // Skeletons
  89291. serializationObject.skeletons = [];
  89292. for (index = 0; index < scene.skeletons.length; index++) {
  89293. var skeleton = scene.skeletons[index];
  89294. if (!skeleton.doNotSerialize) {
  89295. serializationObject.skeletons.push(skeleton.serialize());
  89296. }
  89297. }
  89298. // Transform nodes
  89299. serializationObject.transformNodes = [];
  89300. for (index = 0; index < scene.transformNodes.length; index++) {
  89301. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  89302. }
  89303. // Geometries
  89304. serializationObject.geometries = {};
  89305. serializationObject.geometries.boxes = [];
  89306. serializationObject.geometries.spheres = [];
  89307. serializationObject.geometries.cylinders = [];
  89308. serializationObject.geometries.toruses = [];
  89309. serializationObject.geometries.grounds = [];
  89310. serializationObject.geometries.planes = [];
  89311. serializationObject.geometries.torusKnots = [];
  89312. serializationObject.geometries.vertexData = [];
  89313. serializedGeometries = [];
  89314. var geometries = scene.getGeometries();
  89315. for (index = 0; index < geometries.length; index++) {
  89316. var geometry = geometries[index];
  89317. if (geometry.isReady()) {
  89318. serializeGeometry(geometry, serializationObject.geometries);
  89319. }
  89320. }
  89321. // Meshes
  89322. serializationObject.meshes = [];
  89323. for (index = 0; index < scene.meshes.length; index++) {
  89324. var abstractMesh = scene.meshes[index];
  89325. if (abstractMesh instanceof BABYLON.Mesh) {
  89326. var mesh = abstractMesh;
  89327. if (!mesh.doNotSerialize) {
  89328. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  89329. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  89330. }
  89331. }
  89332. }
  89333. }
  89334. // Particles Systems
  89335. serializationObject.particleSystems = [];
  89336. for (index = 0; index < scene.particleSystems.length; index++) {
  89337. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  89338. }
  89339. // Lens flares
  89340. serializationObject.lensFlareSystems = [];
  89341. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  89342. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  89343. }
  89344. // Shadows
  89345. serializationObject.shadowGenerators = [];
  89346. for (index = 0; index < scene.lights.length; index++) {
  89347. light = scene.lights[index];
  89348. var shadowGenerator = light.getShadowGenerator();
  89349. if (shadowGenerator) {
  89350. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  89351. }
  89352. }
  89353. // Action Manager
  89354. if (scene.actionManager) {
  89355. serializationObject.actions = scene.actionManager.serialize("scene");
  89356. }
  89357. // Audio
  89358. serializationObject.sounds = [];
  89359. for (index = 0; index < scene.soundTracks.length; index++) {
  89360. var soundtrack = scene.soundTracks[index];
  89361. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  89362. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  89363. }
  89364. }
  89365. return serializationObject;
  89366. };
  89367. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  89368. if (withParents === void 0) { withParents = false; }
  89369. if (withChildren === void 0) { withChildren = false; }
  89370. var serializationObject = {};
  89371. SceneSerializer.ClearCache();
  89372. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  89373. if (withParents || withChildren) {
  89374. //deliberate for loop! not for each, appended should be processed as well.
  89375. for (var i = 0; i < toSerialize.length; ++i) {
  89376. if (withChildren) {
  89377. toSerialize[i].getDescendants().forEach(function (node) {
  89378. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  89379. toSerialize.push(node);
  89380. }
  89381. });
  89382. }
  89383. //make sure the array doesn't contain the object already
  89384. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  89385. toSerialize.push(toSerialize[i].parent);
  89386. }
  89387. }
  89388. }
  89389. toSerialize.forEach(function (mesh) {
  89390. finalizeSingleMesh(mesh, serializationObject);
  89391. });
  89392. return serializationObject;
  89393. };
  89394. return SceneSerializer;
  89395. }());
  89396. BABYLON.SceneSerializer = SceneSerializer;
  89397. })(BABYLON || (BABYLON = {}));
  89398. //# sourceMappingURL=babylon.sceneSerializer.js.map
  89399. "use strict";
  89400. var BABYLON;
  89401. (function (BABYLON) {
  89402. var ReflectionProbe = /** @class */ (function () {
  89403. function ReflectionProbe(name, size, scene, generateMipMaps) {
  89404. if (generateMipMaps === void 0) { generateMipMaps = true; }
  89405. var _this = this;
  89406. this.name = name;
  89407. this._viewMatrix = BABYLON.Matrix.Identity();
  89408. this._target = BABYLON.Vector3.Zero();
  89409. this._add = BABYLON.Vector3.Zero();
  89410. this._invertYAxis = false;
  89411. this.position = BABYLON.Vector3.Zero();
  89412. this._scene = scene;
  89413. this._scene.reflectionProbes.push(this);
  89414. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  89415. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  89416. switch (faceIndex) {
  89417. case 0:
  89418. _this._add.copyFromFloats(1, 0, 0);
  89419. break;
  89420. case 1:
  89421. _this._add.copyFromFloats(-1, 0, 0);
  89422. break;
  89423. case 2:
  89424. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  89425. break;
  89426. case 3:
  89427. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  89428. break;
  89429. case 4:
  89430. _this._add.copyFromFloats(0, 0, 1);
  89431. break;
  89432. case 5:
  89433. _this._add.copyFromFloats(0, 0, -1);
  89434. break;
  89435. }
  89436. if (_this._attachedMesh) {
  89437. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  89438. }
  89439. _this.position.addToRef(_this._add, _this._target);
  89440. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  89441. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  89442. scene._forcedViewPosition = _this.position;
  89443. });
  89444. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  89445. scene._forcedViewPosition = null;
  89446. scene.updateTransformMatrix(true);
  89447. });
  89448. if (scene.activeCamera) {
  89449. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  89450. }
  89451. }
  89452. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  89453. get: function () {
  89454. return this._renderTargetTexture.samples;
  89455. },
  89456. set: function (value) {
  89457. this._renderTargetTexture.samples = value;
  89458. },
  89459. enumerable: true,
  89460. configurable: true
  89461. });
  89462. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  89463. get: function () {
  89464. return this._renderTargetTexture.refreshRate;
  89465. },
  89466. set: function (value) {
  89467. this._renderTargetTexture.refreshRate = value;
  89468. },
  89469. enumerable: true,
  89470. configurable: true
  89471. });
  89472. ReflectionProbe.prototype.getScene = function () {
  89473. return this._scene;
  89474. };
  89475. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  89476. get: function () {
  89477. return this._renderTargetTexture;
  89478. },
  89479. enumerable: true,
  89480. configurable: true
  89481. });
  89482. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  89483. get: function () {
  89484. return this._renderTargetTexture.renderList;
  89485. },
  89486. enumerable: true,
  89487. configurable: true
  89488. });
  89489. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  89490. this._attachedMesh = mesh;
  89491. };
  89492. /**
  89493. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  89494. *
  89495. * @param renderingGroupId The rendering group id corresponding to its index
  89496. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  89497. */
  89498. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  89499. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  89500. };
  89501. ReflectionProbe.prototype.dispose = function () {
  89502. var index = this._scene.reflectionProbes.indexOf(this);
  89503. if (index !== -1) {
  89504. // Remove from the scene if found
  89505. this._scene.reflectionProbes.splice(index, 1);
  89506. }
  89507. if (this._renderTargetTexture) {
  89508. this._renderTargetTexture.dispose();
  89509. this._renderTargetTexture = null;
  89510. }
  89511. };
  89512. return ReflectionProbe;
  89513. }());
  89514. BABYLON.ReflectionProbe = ReflectionProbe;
  89515. })(BABYLON || (BABYLON = {}));
  89516. //# sourceMappingURL=babylon.reflectionProbe.js.map
  89517. "use strict";
  89518. var BABYLON;
  89519. (function (BABYLON) {
  89520. var Layer = /** @class */ (function () {
  89521. function Layer(name, imgUrl, scene, isBackground, color) {
  89522. this.name = name;
  89523. this.scale = new BABYLON.Vector2(1, 1);
  89524. this.offset = new BABYLON.Vector2(0, 0);
  89525. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  89526. this.layerMask = 0x0FFFFFFF;
  89527. this._vertexBuffers = {};
  89528. // Events
  89529. /**
  89530. * An event triggered when the layer is disposed.
  89531. */
  89532. this.onDisposeObservable = new BABYLON.Observable();
  89533. /**
  89534. * An event triggered before rendering the scene
  89535. */
  89536. this.onBeforeRenderObservable = new BABYLON.Observable();
  89537. /**
  89538. * An event triggered after rendering the scene
  89539. */
  89540. this.onAfterRenderObservable = new BABYLON.Observable();
  89541. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  89542. this.isBackground = isBackground === undefined ? true : isBackground;
  89543. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  89544. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  89545. this._scene.layers.push(this);
  89546. var engine = this._scene.getEngine();
  89547. // VBO
  89548. var vertices = [];
  89549. vertices.push(1, 1);
  89550. vertices.push(-1, 1);
  89551. vertices.push(-1, -1);
  89552. vertices.push(1, -1);
  89553. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89554. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89555. this._createIndexBuffer();
  89556. // Effects
  89557. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  89558. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  89559. }
  89560. Object.defineProperty(Layer.prototype, "onDispose", {
  89561. set: function (callback) {
  89562. if (this._onDisposeObserver) {
  89563. this.onDisposeObservable.remove(this._onDisposeObserver);
  89564. }
  89565. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89566. },
  89567. enumerable: true,
  89568. configurable: true
  89569. });
  89570. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  89571. set: function (callback) {
  89572. if (this._onBeforeRenderObserver) {
  89573. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  89574. }
  89575. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  89576. },
  89577. enumerable: true,
  89578. configurable: true
  89579. });
  89580. Object.defineProperty(Layer.prototype, "onAfterRender", {
  89581. set: function (callback) {
  89582. if (this._onAfterRenderObserver) {
  89583. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89584. }
  89585. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  89586. },
  89587. enumerable: true,
  89588. configurable: true
  89589. });
  89590. Layer.prototype._createIndexBuffer = function () {
  89591. var engine = this._scene.getEngine();
  89592. // Indices
  89593. var indices = [];
  89594. indices.push(0);
  89595. indices.push(1);
  89596. indices.push(2);
  89597. indices.push(0);
  89598. indices.push(2);
  89599. indices.push(3);
  89600. this._indexBuffer = engine.createIndexBuffer(indices);
  89601. };
  89602. Layer.prototype._rebuild = function () {
  89603. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89604. if (vb) {
  89605. vb._rebuild();
  89606. }
  89607. this._createIndexBuffer();
  89608. };
  89609. Layer.prototype.render = function () {
  89610. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  89611. // Check
  89612. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  89613. return;
  89614. var engine = this._scene.getEngine();
  89615. this.onBeforeRenderObservable.notifyObservers(this);
  89616. // Render
  89617. engine.enableEffect(currentEffect);
  89618. engine.setState(false);
  89619. // Texture
  89620. currentEffect.setTexture("textureSampler", this.texture);
  89621. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  89622. // Color
  89623. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  89624. // Scale / offset
  89625. currentEffect.setVector2("offset", this.offset);
  89626. currentEffect.setVector2("scale", this.scale);
  89627. // VBOs
  89628. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89629. // Draw order
  89630. if (!this.alphaTest) {
  89631. engine.setAlphaMode(this.alphaBlendingMode);
  89632. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89633. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89634. }
  89635. else {
  89636. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89637. }
  89638. this.onAfterRenderObservable.notifyObservers(this);
  89639. };
  89640. Layer.prototype.dispose = function () {
  89641. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89642. if (vertexBuffer) {
  89643. vertexBuffer.dispose();
  89644. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89645. }
  89646. if (this._indexBuffer) {
  89647. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89648. this._indexBuffer = null;
  89649. }
  89650. if (this.texture) {
  89651. this.texture.dispose();
  89652. this.texture = null;
  89653. }
  89654. // Remove from scene
  89655. var index = this._scene.layers.indexOf(this);
  89656. this._scene.layers.splice(index, 1);
  89657. // Callback
  89658. this.onDisposeObservable.notifyObservers(this);
  89659. this.onDisposeObservable.clear();
  89660. this.onAfterRenderObservable.clear();
  89661. this.onBeforeRenderObservable.clear();
  89662. };
  89663. return Layer;
  89664. }());
  89665. BABYLON.Layer = Layer;
  89666. })(BABYLON || (BABYLON = {}));
  89667. //# sourceMappingURL=babylon.layer.js.map
  89668. "use strict";
  89669. var BABYLON;
  89670. (function (BABYLON) {
  89671. var TextureTools = /** @class */ (function () {
  89672. function TextureTools() {
  89673. }
  89674. /**
  89675. * Uses the GPU to create a copy texture rescaled at a given size
  89676. * @param texture Texture to copy from
  89677. * @param width Desired width
  89678. * @param height Desired height
  89679. * @return Generated texture
  89680. */
  89681. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  89682. if (useBilinearMode === void 0) { useBilinearMode = true; }
  89683. var scene = texture.getScene();
  89684. var engine = scene.getEngine();
  89685. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  89686. rtt.wrapU = texture.wrapU;
  89687. rtt.wrapV = texture.wrapV;
  89688. rtt.uOffset = texture.uOffset;
  89689. rtt.vOffset = texture.vOffset;
  89690. rtt.uScale = texture.uScale;
  89691. rtt.vScale = texture.vScale;
  89692. rtt.uAng = texture.uAng;
  89693. rtt.vAng = texture.vAng;
  89694. rtt.wAng = texture.wAng;
  89695. rtt.coordinatesIndex = texture.coordinatesIndex;
  89696. rtt.level = texture.level;
  89697. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  89698. rtt._texture.isReady = false;
  89699. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89700. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89701. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89702. passPostProcess.getEffect().executeWhenCompiled(function () {
  89703. passPostProcess.onApply = function (effect) {
  89704. effect.setTexture("textureSampler", texture);
  89705. };
  89706. var internalTexture = rtt.getInternalTexture();
  89707. if (internalTexture) {
  89708. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  89709. engine.unBindFramebuffer(internalTexture);
  89710. rtt.disposeFramebufferObjects();
  89711. passPostProcess.dispose();
  89712. internalTexture.isReady = true;
  89713. }
  89714. });
  89715. return rtt;
  89716. };
  89717. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  89718. if (!scene._environmentBRDFTexture) {
  89719. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89720. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89721. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89722. scene._environmentBRDFTexture = texture;
  89723. }
  89724. return scene._environmentBRDFTexture;
  89725. };
  89726. 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=";
  89727. return TextureTools;
  89728. }());
  89729. BABYLON.TextureTools = TextureTools;
  89730. })(BABYLON || (BABYLON = {}));
  89731. //# sourceMappingURL=babylon.textureTools.js.map
  89732. "use strict";
  89733. var BABYLON;
  89734. (function (BABYLON) {
  89735. var FramingBehavior = /** @class */ (function () {
  89736. function FramingBehavior() {
  89737. this._mode = FramingBehavior.FitFrustumSidesMode;
  89738. this._radiusScale = 1.0;
  89739. this._positionScale = 0.5;
  89740. this._defaultElevation = 0.3;
  89741. this._elevationReturnTime = 1500;
  89742. this._elevationReturnWaitTime = 1000;
  89743. this._zoomStopsAnimation = false;
  89744. this._framingTime = 1500;
  89745. this._isPointerDown = false;
  89746. this._lastInteractionTime = -Infinity;
  89747. // Framing control
  89748. this._animatables = new Array();
  89749. this._betaIsAnimating = false;
  89750. }
  89751. Object.defineProperty(FramingBehavior.prototype, "name", {
  89752. get: function () {
  89753. return "Framing";
  89754. },
  89755. enumerable: true,
  89756. configurable: true
  89757. });
  89758. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89759. /**
  89760. * Gets current mode used by the behavior.
  89761. */
  89762. get: function () {
  89763. return this._mode;
  89764. },
  89765. /**
  89766. * Sets the current mode used by the behavior
  89767. */
  89768. set: function (mode) {
  89769. this._mode = mode;
  89770. },
  89771. enumerable: true,
  89772. configurable: true
  89773. });
  89774. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89775. /**
  89776. * Gets the scale applied to the radius
  89777. */
  89778. get: function () {
  89779. return this._radiusScale;
  89780. },
  89781. /**
  89782. * Sets the scale applied to the radius (1 by default)
  89783. */
  89784. set: function (radius) {
  89785. this._radiusScale = radius;
  89786. },
  89787. enumerable: true,
  89788. configurable: true
  89789. });
  89790. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89791. /**
  89792. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89793. */
  89794. get: function () {
  89795. return this._positionScale;
  89796. },
  89797. /**
  89798. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89799. */
  89800. set: function (scale) {
  89801. this._positionScale = scale;
  89802. },
  89803. enumerable: true,
  89804. configurable: true
  89805. });
  89806. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89807. /**
  89808. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89809. * behaviour is triggered, in radians.
  89810. */
  89811. get: function () {
  89812. return this._defaultElevation;
  89813. },
  89814. /**
  89815. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89816. * behaviour is triggered, in radians.
  89817. */
  89818. set: function (elevation) {
  89819. this._defaultElevation = elevation;
  89820. },
  89821. enumerable: true,
  89822. configurable: true
  89823. });
  89824. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89825. /**
  89826. * Gets the time (in milliseconds) taken to return to the default beta position.
  89827. * Negative value indicates camera should not return to default.
  89828. */
  89829. get: function () {
  89830. return this._elevationReturnTime;
  89831. },
  89832. /**
  89833. * Sets the time (in milliseconds) taken to return to the default beta position.
  89834. * Negative value indicates camera should not return to default.
  89835. */
  89836. set: function (speed) {
  89837. this._elevationReturnTime = speed;
  89838. },
  89839. enumerable: true,
  89840. configurable: true
  89841. });
  89842. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89843. /**
  89844. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89845. */
  89846. get: function () {
  89847. return this._elevationReturnWaitTime;
  89848. },
  89849. /**
  89850. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89851. */
  89852. set: function (time) {
  89853. this._elevationReturnWaitTime = time;
  89854. },
  89855. enumerable: true,
  89856. configurable: true
  89857. });
  89858. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89859. /**
  89860. * Gets the flag that indicates if user zooming should stop animation.
  89861. */
  89862. get: function () {
  89863. return this._zoomStopsAnimation;
  89864. },
  89865. /**
  89866. * Sets the flag that indicates if user zooming should stop animation.
  89867. */
  89868. set: function (flag) {
  89869. this._zoomStopsAnimation = flag;
  89870. },
  89871. enumerable: true,
  89872. configurable: true
  89873. });
  89874. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89875. /**
  89876. * Gets the transition time when framing the mesh, in milliseconds
  89877. */
  89878. get: function () {
  89879. return this._framingTime;
  89880. },
  89881. /**
  89882. * Sets the transition time when framing the mesh, in milliseconds
  89883. */
  89884. set: function (time) {
  89885. this._framingTime = time;
  89886. },
  89887. enumerable: true,
  89888. configurable: true
  89889. });
  89890. FramingBehavior.prototype.init = function () {
  89891. // Do notihng
  89892. };
  89893. FramingBehavior.prototype.attach = function (camera) {
  89894. var _this = this;
  89895. this._attachedCamera = camera;
  89896. var scene = this._attachedCamera.getScene();
  89897. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89898. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89899. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89900. _this._isPointerDown = true;
  89901. return;
  89902. }
  89903. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89904. _this._isPointerDown = false;
  89905. }
  89906. });
  89907. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89908. if (mesh) {
  89909. _this.zoomOnMesh(mesh);
  89910. }
  89911. });
  89912. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89913. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89914. _this._applyUserInteraction();
  89915. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89916. // back to the default position after a given timeout
  89917. _this._maintainCameraAboveGround();
  89918. });
  89919. };
  89920. FramingBehavior.prototype.detach = function () {
  89921. if (!this._attachedCamera) {
  89922. return;
  89923. }
  89924. var scene = this._attachedCamera.getScene();
  89925. if (this._onPrePointerObservableObserver) {
  89926. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89927. }
  89928. if (this._onAfterCheckInputsObserver) {
  89929. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89930. }
  89931. if (this._onMeshTargetChangedObserver) {
  89932. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89933. }
  89934. this._attachedCamera = null;
  89935. };
  89936. /**
  89937. * Targets the given mesh and updates zoom level accordingly.
  89938. * @param mesh The mesh to target.
  89939. * @param radius Optional. If a cached radius position already exists, overrides default.
  89940. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89941. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89942. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89943. */
  89944. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89945. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89946. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89947. mesh.computeWorldMatrix(true);
  89948. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89949. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89950. };
  89951. /**
  89952. * Targets the given mesh with its children and updates zoom level accordingly.
  89953. * @param mesh The mesh to target.
  89954. * @param radius Optional. If a cached radius position already exists, overrides default.
  89955. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89956. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89957. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89958. */
  89959. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89960. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89961. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89962. mesh.computeWorldMatrix(true);
  89963. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89964. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89965. };
  89966. /**
  89967. * Targets the given meshes with their children and updates zoom level accordingly.
  89968. * @param meshes The mesh to target.
  89969. * @param radius Optional. If a cached radius position already exists, overrides default.
  89970. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89971. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89972. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89973. */
  89974. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89975. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89976. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89977. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89978. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89979. for (var i = 0; i < meshes.length; i++) {
  89980. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89981. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89982. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89983. }
  89984. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89985. };
  89986. /**
  89987. * Targets the given mesh and updates zoom level accordingly.
  89988. * @param mesh The mesh to target.
  89989. * @param radius Optional. If a cached radius position already exists, overrides default.
  89990. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89991. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89992. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89993. */
  89994. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89995. var _this = this;
  89996. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89997. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89998. var zoomTarget;
  89999. if (!this._attachedCamera) {
  90000. return;
  90001. }
  90002. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  90003. var bottom = minimumWorld.y;
  90004. var top = maximumWorld.y;
  90005. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  90006. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  90007. if (focusOnOriginXZ) {
  90008. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  90009. }
  90010. else {
  90011. var centerWorld = minimumWorld.add(radiusWorld);
  90012. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  90013. }
  90014. if (!this._vectorTransition) {
  90015. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  90016. }
  90017. this._betaIsAnimating = true;
  90018. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  90019. if (animatable) {
  90020. this._animatables.push(animatable);
  90021. }
  90022. // sets the radius and lower radius bounds
  90023. // Small delta ensures camera is not always at lower zoom limit.
  90024. var radius = 0;
  90025. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  90026. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  90027. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  90028. radius = position;
  90029. }
  90030. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  90031. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  90032. if (this._attachedCamera.lowerRadiusLimit === null) {
  90033. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  90034. }
  90035. }
  90036. // Set sensibilities
  90037. var extend = maximumWorld.subtract(minimumWorld).length();
  90038. this._attachedCamera.panningSensibility = 5000 / extend;
  90039. this._attachedCamera.wheelPrecision = 100 / radius;
  90040. // transition to new radius
  90041. if (!this._radiusTransition) {
  90042. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  90043. }
  90044. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  90045. _this.stopAllAnimations();
  90046. if (onAnimationEnd) {
  90047. onAnimationEnd();
  90048. }
  90049. if (_this._attachedCamera) {
  90050. _this._attachedCamera.storeState();
  90051. }
  90052. });
  90053. if (animatable) {
  90054. this._animatables.push(animatable);
  90055. }
  90056. };
  90057. /**
  90058. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  90059. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  90060. * frustum width.
  90061. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  90062. * to fully enclose the mesh in the viewing frustum.
  90063. */
  90064. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  90065. var size = maximumWorld.subtract(minimumWorld);
  90066. var boxVectorGlobalDiagonal = size.length();
  90067. var frustumSlope = this._getFrustumSlope();
  90068. // Formula for setting distance
  90069. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  90070. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  90071. // Horizon distance
  90072. var radius = radiusWithoutFraming * this._radiusScale;
  90073. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  90074. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  90075. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  90076. var camera = this._attachedCamera;
  90077. if (!camera) {
  90078. return 0;
  90079. }
  90080. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  90081. // Don't exceed the requested limit
  90082. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  90083. }
  90084. // Don't exceed the upper radius limit
  90085. if (camera.upperRadiusLimit) {
  90086. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  90087. }
  90088. return distance;
  90089. };
  90090. /**
  90091. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  90092. * is automatically returned to its default position (expected to be above ground plane).
  90093. */
  90094. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  90095. var _this = this;
  90096. if (this._elevationReturnTime < 0) {
  90097. return;
  90098. }
  90099. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  90100. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  90101. var limitBeta = Math.PI * 0.5;
  90102. // Bring the camera back up if below the ground plane
  90103. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  90104. this._betaIsAnimating = true;
  90105. //Transition to new position
  90106. this.stopAllAnimations();
  90107. if (!this._betaTransition) {
  90108. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  90109. }
  90110. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  90111. _this._clearAnimationLocks();
  90112. _this.stopAllAnimations();
  90113. });
  90114. if (animatabe) {
  90115. this._animatables.push(animatabe);
  90116. }
  90117. }
  90118. };
  90119. /**
  90120. * Returns the frustum slope based on the canvas ratio and camera FOV
  90121. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  90122. */
  90123. FramingBehavior.prototype._getFrustumSlope = function () {
  90124. // Calculate the viewport ratio
  90125. // Aspect Ratio is Height/Width.
  90126. var camera = this._attachedCamera;
  90127. if (!camera) {
  90128. return BABYLON.Vector2.Zero();
  90129. }
  90130. var engine = camera.getScene().getEngine();
  90131. var aspectRatio = engine.getAspectRatio(camera);
  90132. // Camera FOV is the vertical field of view (top-bottom) in radians.
  90133. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  90134. var frustumSlopeY = Math.tan(camera.fov / 2);
  90135. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  90136. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  90137. // along the forward vector.
  90138. var frustumSlopeX = frustumSlopeY * aspectRatio;
  90139. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  90140. };
  90141. /**
  90142. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  90143. */
  90144. FramingBehavior.prototype._clearAnimationLocks = function () {
  90145. this._betaIsAnimating = false;
  90146. };
  90147. /**
  90148. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  90149. */
  90150. FramingBehavior.prototype._applyUserInteraction = function () {
  90151. if (this.isUserIsMoving) {
  90152. this._lastInteractionTime = BABYLON.Tools.Now;
  90153. this.stopAllAnimations();
  90154. this._clearAnimationLocks();
  90155. }
  90156. };
  90157. /**
  90158. * Stops and removes all animations that have been applied to the camera
  90159. */
  90160. FramingBehavior.prototype.stopAllAnimations = function () {
  90161. if (this._attachedCamera) {
  90162. this._attachedCamera.animations = [];
  90163. }
  90164. while (this._animatables.length) {
  90165. if (this._animatables[0]) {
  90166. this._animatables[0].onAnimationEnd = null;
  90167. this._animatables[0].stop();
  90168. }
  90169. this._animatables.shift();
  90170. }
  90171. };
  90172. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  90173. /**
  90174. * Gets a value indicating if the user is moving the camera
  90175. */
  90176. get: function () {
  90177. if (!this._attachedCamera) {
  90178. return false;
  90179. }
  90180. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  90181. this._attachedCamera.inertialBetaOffset !== 0 ||
  90182. this._attachedCamera.inertialRadiusOffset !== 0 ||
  90183. this._attachedCamera.inertialPanningX !== 0 ||
  90184. this._attachedCamera.inertialPanningY !== 0 ||
  90185. this._isPointerDown;
  90186. },
  90187. enumerable: true,
  90188. configurable: true
  90189. });
  90190. /**
  90191. * The easing function used by animations
  90192. */
  90193. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  90194. /**
  90195. * The easing mode used by animations
  90196. */
  90197. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  90198. // Statics
  90199. /**
  90200. * The camera can move all the way towards the mesh.
  90201. */
  90202. FramingBehavior.IgnoreBoundsSizeMode = 0;
  90203. /**
  90204. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  90205. */
  90206. FramingBehavior.FitFrustumSidesMode = 1;
  90207. return FramingBehavior;
  90208. }());
  90209. BABYLON.FramingBehavior = FramingBehavior;
  90210. })(BABYLON || (BABYLON = {}));
  90211. //# sourceMappingURL=babylon.framingBehavior.js.map
  90212. "use strict";
  90213. var BABYLON;
  90214. (function (BABYLON) {
  90215. /**
  90216. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  90217. */
  90218. var BouncingBehavior = /** @class */ (function () {
  90219. function BouncingBehavior() {
  90220. /**
  90221. * The duration of the animation, in milliseconds
  90222. */
  90223. this.transitionDuration = 450;
  90224. /**
  90225. * Length of the distance animated by the transition when lower radius is reached
  90226. */
  90227. this.lowerRadiusTransitionRange = 2;
  90228. /**
  90229. * Length of the distance animated by the transition when upper radius is reached
  90230. */
  90231. this.upperRadiusTransitionRange = -2;
  90232. this._autoTransitionRange = false;
  90233. // Animations
  90234. this._radiusIsAnimating = false;
  90235. this._radiusBounceTransition = null;
  90236. this._animatables = new Array();
  90237. }
  90238. Object.defineProperty(BouncingBehavior.prototype, "name", {
  90239. get: function () {
  90240. return "Bouncing";
  90241. },
  90242. enumerable: true,
  90243. configurable: true
  90244. });
  90245. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  90246. /**
  90247. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  90248. */
  90249. get: function () {
  90250. return this._autoTransitionRange;
  90251. },
  90252. /**
  90253. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  90254. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  90255. */
  90256. set: function (value) {
  90257. var _this = this;
  90258. if (this._autoTransitionRange === value) {
  90259. return;
  90260. }
  90261. this._autoTransitionRange = value;
  90262. var camera = this._attachedCamera;
  90263. if (!camera) {
  90264. return;
  90265. }
  90266. if (value) {
  90267. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  90268. if (!mesh) {
  90269. return;
  90270. }
  90271. mesh.computeWorldMatrix(true);
  90272. var diagonal = mesh.getBoundingInfo().diagonalLength;
  90273. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  90274. _this.upperRadiusTransitionRange = diagonal * 0.05;
  90275. });
  90276. }
  90277. else if (this._onMeshTargetChangedObserver) {
  90278. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  90279. }
  90280. },
  90281. enumerable: true,
  90282. configurable: true
  90283. });
  90284. BouncingBehavior.prototype.init = function () {
  90285. // Do notihng
  90286. };
  90287. BouncingBehavior.prototype.attach = function (camera) {
  90288. var _this = this;
  90289. this._attachedCamera = camera;
  90290. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  90291. if (!_this._attachedCamera) {
  90292. return;
  90293. }
  90294. // Add the bounce animation to the lower radius limit
  90295. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  90296. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  90297. }
  90298. // Add the bounce animation to the upper radius limit
  90299. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  90300. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  90301. }
  90302. });
  90303. };
  90304. BouncingBehavior.prototype.detach = function () {
  90305. if (!this._attachedCamera) {
  90306. return;
  90307. }
  90308. if (this._onAfterCheckInputsObserver) {
  90309. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  90310. }
  90311. if (this._onMeshTargetChangedObserver) {
  90312. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  90313. }
  90314. this._attachedCamera = null;
  90315. };
  90316. /**
  90317. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  90318. * @param radiusLimit The limit to check against.
  90319. * @return Bool to indicate if at limit.
  90320. */
  90321. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  90322. if (!this._attachedCamera) {
  90323. return false;
  90324. }
  90325. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  90326. return true;
  90327. }
  90328. return false;
  90329. };
  90330. /**
  90331. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  90332. * @param radiusDelta The delta by which to animate to. Can be negative.
  90333. */
  90334. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  90335. var _this = this;
  90336. if (!this._attachedCamera) {
  90337. return;
  90338. }
  90339. if (!this._radiusBounceTransition) {
  90340. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  90341. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  90342. }
  90343. // Prevent zoom until bounce has completed
  90344. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  90345. this._attachedCamera.wheelPrecision = Infinity;
  90346. this._attachedCamera.inertialRadiusOffset = 0;
  90347. // Animate to the radius limit
  90348. this.stopAllAnimations();
  90349. this._radiusIsAnimating = true;
  90350. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  90351. if (animatable) {
  90352. this._animatables.push(animatable);
  90353. }
  90354. };
  90355. /**
  90356. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  90357. */
  90358. BouncingBehavior.prototype._clearAnimationLocks = function () {
  90359. this._radiusIsAnimating = false;
  90360. if (this._attachedCamera) {
  90361. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  90362. }
  90363. };
  90364. /**
  90365. * Stops and removes all animations that have been applied to the camera
  90366. */
  90367. BouncingBehavior.prototype.stopAllAnimations = function () {
  90368. if (this._attachedCamera) {
  90369. this._attachedCamera.animations = [];
  90370. }
  90371. while (this._animatables.length) {
  90372. this._animatables[0].onAnimationEnd = null;
  90373. this._animatables[0].stop();
  90374. this._animatables.shift();
  90375. }
  90376. };
  90377. /**
  90378. * The easing function used by animations
  90379. */
  90380. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  90381. /**
  90382. * The easing mode used by animations
  90383. */
  90384. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  90385. return BouncingBehavior;
  90386. }());
  90387. BABYLON.BouncingBehavior = BouncingBehavior;
  90388. })(BABYLON || (BABYLON = {}));
  90389. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  90390. "use strict";
  90391. var BABYLON;
  90392. (function (BABYLON) {
  90393. var AutoRotationBehavior = /** @class */ (function () {
  90394. function AutoRotationBehavior() {
  90395. this._zoomStopsAnimation = false;
  90396. this._idleRotationSpeed = 0.05;
  90397. this._idleRotationWaitTime = 2000;
  90398. this._idleRotationSpinupTime = 2000;
  90399. this._isPointerDown = false;
  90400. this._lastFrameTime = null;
  90401. this._lastInteractionTime = -Infinity;
  90402. this._cameraRotationSpeed = 0;
  90403. this._lastFrameRadius = 0;
  90404. }
  90405. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  90406. get: function () {
  90407. return "AutoRotation";
  90408. },
  90409. enumerable: true,
  90410. configurable: true
  90411. });
  90412. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  90413. /**
  90414. * Gets the flag that indicates if user zooming should stop animation.
  90415. */
  90416. get: function () {
  90417. return this._zoomStopsAnimation;
  90418. },
  90419. /**
  90420. * Sets the flag that indicates if user zooming should stop animation.
  90421. */
  90422. set: function (flag) {
  90423. this._zoomStopsAnimation = flag;
  90424. },
  90425. enumerable: true,
  90426. configurable: true
  90427. });
  90428. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  90429. /**
  90430. * Gets the default speed at which the camera rotates around the model.
  90431. */
  90432. get: function () {
  90433. return this._idleRotationSpeed;
  90434. },
  90435. /**
  90436. * Sets the default speed at which the camera rotates around the model.
  90437. */
  90438. set: function (speed) {
  90439. this._idleRotationSpeed = speed;
  90440. },
  90441. enumerable: true,
  90442. configurable: true
  90443. });
  90444. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  90445. /**
  90446. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  90447. */
  90448. get: function () {
  90449. return this._idleRotationWaitTime;
  90450. },
  90451. /**
  90452. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  90453. */
  90454. set: function (time) {
  90455. this._idleRotationWaitTime = time;
  90456. },
  90457. enumerable: true,
  90458. configurable: true
  90459. });
  90460. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  90461. /**
  90462. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  90463. */
  90464. get: function () {
  90465. return this._idleRotationSpinupTime;
  90466. },
  90467. /**
  90468. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  90469. */
  90470. set: function (time) {
  90471. this._idleRotationSpinupTime = time;
  90472. },
  90473. enumerable: true,
  90474. configurable: true
  90475. });
  90476. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  90477. /**
  90478. * Gets a value indicating if the camera is currently rotating because of this behavior
  90479. */
  90480. get: function () {
  90481. return Math.abs(this._cameraRotationSpeed) > 0;
  90482. },
  90483. enumerable: true,
  90484. configurable: true
  90485. });
  90486. AutoRotationBehavior.prototype.init = function () {
  90487. // Do notihng
  90488. };
  90489. AutoRotationBehavior.prototype.attach = function (camera) {
  90490. var _this = this;
  90491. this._attachedCamera = camera;
  90492. var scene = this._attachedCamera.getScene();
  90493. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  90494. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90495. _this._isPointerDown = true;
  90496. return;
  90497. }
  90498. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  90499. _this._isPointerDown = false;
  90500. }
  90501. });
  90502. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  90503. var now = BABYLON.Tools.Now;
  90504. var dt = 0;
  90505. if (_this._lastFrameTime != null) {
  90506. dt = now - _this._lastFrameTime;
  90507. }
  90508. _this._lastFrameTime = now;
  90509. // Stop the animation if there is user interaction and the animation should stop for this interaction
  90510. _this._applyUserInteraction();
  90511. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  90512. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  90513. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  90514. // Step camera rotation by rotation speed
  90515. if (_this._attachedCamera) {
  90516. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  90517. }
  90518. });
  90519. };
  90520. AutoRotationBehavior.prototype.detach = function () {
  90521. if (!this._attachedCamera) {
  90522. return;
  90523. }
  90524. var scene = this._attachedCamera.getScene();
  90525. if (this._onPrePointerObservableObserver) {
  90526. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  90527. }
  90528. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  90529. this._attachedCamera = null;
  90530. };
  90531. /**
  90532. * Returns true if user is scrolling.
  90533. * @return true if user is scrolling.
  90534. */
  90535. AutoRotationBehavior.prototype._userIsZooming = function () {
  90536. if (!this._attachedCamera) {
  90537. return false;
  90538. }
  90539. return this._attachedCamera.inertialRadiusOffset !== 0;
  90540. };
  90541. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  90542. if (!this._attachedCamera) {
  90543. return false;
  90544. }
  90545. var zoomHasHitLimit = false;
  90546. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  90547. zoomHasHitLimit = true;
  90548. }
  90549. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  90550. this._lastFrameRadius = this._attachedCamera.radius;
  90551. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  90552. };
  90553. /**
  90554. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  90555. */
  90556. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  90557. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  90558. this._lastInteractionTime = BABYLON.Tools.Now;
  90559. }
  90560. };
  90561. // Tools
  90562. AutoRotationBehavior.prototype._userIsMoving = function () {
  90563. if (!this._attachedCamera) {
  90564. return false;
  90565. }
  90566. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  90567. this._attachedCamera.inertialBetaOffset !== 0 ||
  90568. this._attachedCamera.inertialRadiusOffset !== 0 ||
  90569. this._attachedCamera.inertialPanningX !== 0 ||
  90570. this._attachedCamera.inertialPanningY !== 0 ||
  90571. this._isPointerDown;
  90572. };
  90573. return AutoRotationBehavior;
  90574. }());
  90575. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  90576. })(BABYLON || (BABYLON = {}));
  90577. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  90578. "use strict";
  90579. var BABYLON;
  90580. (function (BABYLON) {
  90581. var NullEngineOptions = /** @class */ (function () {
  90582. function NullEngineOptions() {
  90583. this.renderWidth = 512;
  90584. this.renderHeight = 256;
  90585. this.textureSize = 512;
  90586. this.deterministicLockstep = false;
  90587. this.lockstepMaxSteps = 4;
  90588. }
  90589. return NullEngineOptions;
  90590. }());
  90591. BABYLON.NullEngineOptions = NullEngineOptions;
  90592. /**
  90593. * The null engine class provides support for headless version of babylon.js.
  90594. * This can be used in server side scenario or for testing purposes
  90595. */
  90596. var NullEngine = /** @class */ (function (_super) {
  90597. __extends(NullEngine, _super);
  90598. function NullEngine(options) {
  90599. if (options === void 0) { options = new NullEngineOptions(); }
  90600. var _this = _super.call(this, null) || this;
  90601. if (options.deterministicLockstep === undefined) {
  90602. options.deterministicLockstep = false;
  90603. }
  90604. if (options.lockstepMaxSteps === undefined) {
  90605. options.lockstepMaxSteps = 4;
  90606. }
  90607. _this._options = options;
  90608. // Init caps
  90609. // We consider we are on a webgl1 capable device
  90610. _this._caps = new BABYLON.EngineCapabilities();
  90611. _this._caps.maxTexturesImageUnits = 16;
  90612. _this._caps.maxVertexTextureImageUnits = 16;
  90613. _this._caps.maxTextureSize = 512;
  90614. _this._caps.maxCubemapTextureSize = 512;
  90615. _this._caps.maxRenderTextureSize = 512;
  90616. _this._caps.maxVertexAttribs = 16;
  90617. _this._caps.maxVaryingVectors = 16;
  90618. _this._caps.maxFragmentUniformVectors = 16;
  90619. _this._caps.maxVertexUniformVectors = 16;
  90620. // Extensions
  90621. _this._caps.standardDerivatives = false;
  90622. _this._caps.astc = null;
  90623. _this._caps.s3tc = null;
  90624. _this._caps.pvrtc = null;
  90625. _this._caps.etc1 = null;
  90626. _this._caps.etc2 = null;
  90627. _this._caps.textureAnisotropicFilterExtension = null;
  90628. _this._caps.maxAnisotropy = 0;
  90629. _this._caps.uintIndices = false;
  90630. _this._caps.fragmentDepthSupported = false;
  90631. _this._caps.highPrecisionShaderSupported = true;
  90632. _this._caps.colorBufferFloat = false;
  90633. _this._caps.textureFloat = false;
  90634. _this._caps.textureFloatLinearFiltering = false;
  90635. _this._caps.textureFloatRender = false;
  90636. _this._caps.textureHalfFloat = false;
  90637. _this._caps.textureHalfFloatLinearFiltering = false;
  90638. _this._caps.textureHalfFloatRender = false;
  90639. _this._caps.textureLOD = false;
  90640. _this._caps.drawBuffersExtension = false;
  90641. _this._caps.depthTextureExtension = false;
  90642. _this._caps.vertexArrayObject = false;
  90643. _this._caps.instancedArrays = false;
  90644. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  90645. // Wrappers
  90646. if (typeof URL === "undefined") {
  90647. URL = {
  90648. createObjectURL: function () { },
  90649. revokeObjectURL: function () { }
  90650. };
  90651. }
  90652. if (typeof Blob === "undefined") {
  90653. Blob = function () { };
  90654. }
  90655. return _this;
  90656. }
  90657. NullEngine.prototype.isDeterministicLockStep = function () {
  90658. return this._options.deterministicLockstep;
  90659. };
  90660. NullEngine.prototype.getLockstepMaxSteps = function () {
  90661. return this._options.lockstepMaxSteps;
  90662. };
  90663. NullEngine.prototype.getHardwareScalingLevel = function () {
  90664. return 1.0;
  90665. };
  90666. NullEngine.prototype.createVertexBuffer = function (vertices) {
  90667. return {
  90668. capacity: 0,
  90669. references: 1,
  90670. is32Bits: false
  90671. };
  90672. };
  90673. NullEngine.prototype.createIndexBuffer = function (indices) {
  90674. return {
  90675. capacity: 0,
  90676. references: 1,
  90677. is32Bits: false
  90678. };
  90679. };
  90680. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  90681. if (stencil === void 0) { stencil = false; }
  90682. };
  90683. NullEngine.prototype.getRenderWidth = function (useScreen) {
  90684. if (useScreen === void 0) { useScreen = false; }
  90685. if (!useScreen && this._currentRenderTarget) {
  90686. return this._currentRenderTarget.width;
  90687. }
  90688. return this._options.renderWidth;
  90689. };
  90690. NullEngine.prototype.getRenderHeight = function (useScreen) {
  90691. if (useScreen === void 0) { useScreen = false; }
  90692. if (!useScreen && this._currentRenderTarget) {
  90693. return this._currentRenderTarget.height;
  90694. }
  90695. return this._options.renderHeight;
  90696. };
  90697. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  90698. this._cachedViewport = viewport;
  90699. };
  90700. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  90701. return {
  90702. transformFeedback: null,
  90703. __SPECTOR_rebuildProgram: null
  90704. };
  90705. };
  90706. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  90707. return [];
  90708. };
  90709. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  90710. return [];
  90711. };
  90712. NullEngine.prototype.bindSamplers = function (effect) {
  90713. this._currentEffect = null;
  90714. };
  90715. NullEngine.prototype.enableEffect = function (effect) {
  90716. this._currentEffect = effect;
  90717. if (effect.onBind) {
  90718. effect.onBind(effect);
  90719. }
  90720. effect.onBindObservable.notifyObservers(effect);
  90721. };
  90722. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  90723. if (zOffset === void 0) { zOffset = 0; }
  90724. if (reverseSide === void 0) { reverseSide = false; }
  90725. };
  90726. NullEngine.prototype.setIntArray = function (uniform, array) {
  90727. };
  90728. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  90729. };
  90730. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  90731. };
  90732. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90733. };
  90734. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90735. };
  90736. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90737. };
  90738. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90739. };
  90740. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90741. };
  90742. NullEngine.prototype.setArray = function (uniform, array) {
  90743. };
  90744. NullEngine.prototype.setArray2 = function (uniform, array) {
  90745. };
  90746. NullEngine.prototype.setArray3 = function (uniform, array) {
  90747. };
  90748. NullEngine.prototype.setArray4 = function (uniform, array) {
  90749. };
  90750. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90751. };
  90752. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90753. };
  90754. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90755. };
  90756. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90757. };
  90758. NullEngine.prototype.setFloat = function (uniform, value) {
  90759. };
  90760. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90761. };
  90762. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90763. };
  90764. NullEngine.prototype.setBool = function (uniform, bool) {
  90765. };
  90766. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90767. };
  90768. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90769. };
  90770. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90771. };
  90772. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90773. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90774. if (this._alphaMode === mode) {
  90775. return;
  90776. }
  90777. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90778. if (!noDepthWriteChange) {
  90779. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90780. }
  90781. this._alphaMode = mode;
  90782. };
  90783. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90784. };
  90785. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90786. if (this.preventCacheWipeBetweenFrames) {
  90787. return;
  90788. }
  90789. this.resetTextureCache();
  90790. this._currentEffect = null;
  90791. if (bruteForce) {
  90792. this._currentProgram = null;
  90793. this._stencilState.reset();
  90794. this._depthCullingState.reset();
  90795. this._alphaState.reset();
  90796. }
  90797. this._cachedVertexBuffers = null;
  90798. this._cachedIndexBuffer = null;
  90799. this._cachedEffectForVertexBuffers = null;
  90800. };
  90801. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90802. };
  90803. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90804. };
  90805. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90806. };
  90807. NullEngine.prototype._createTexture = function () {
  90808. return {};
  90809. };
  90810. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90812. if (onLoad === void 0) { onLoad = null; }
  90813. if (onError === void 0) { onError = null; }
  90814. if (buffer === void 0) { buffer = null; }
  90815. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90816. var url = String(urlArg);
  90817. texture.url = url;
  90818. texture.generateMipMaps = !noMipmap;
  90819. texture.samplingMode = samplingMode;
  90820. texture.invertY = invertY;
  90821. texture.baseWidth = this._options.textureSize;
  90822. texture.baseHeight = this._options.textureSize;
  90823. texture.width = this._options.textureSize;
  90824. texture.height = this._options.textureSize;
  90825. if (format) {
  90826. texture.format = format;
  90827. }
  90828. texture.isReady = true;
  90829. if (onLoad) {
  90830. onLoad();
  90831. }
  90832. return texture;
  90833. };
  90834. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90835. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90836. if (options !== undefined && typeof options === "object") {
  90837. fullOptions.generateMipMaps = options.generateMipMaps;
  90838. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90839. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90840. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90841. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90842. }
  90843. else {
  90844. fullOptions.generateMipMaps = options;
  90845. fullOptions.generateDepthBuffer = true;
  90846. fullOptions.generateStencilBuffer = false;
  90847. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90848. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90849. }
  90850. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90851. var width = size.width || size;
  90852. var height = size.height || size;
  90853. texture._depthStencilBuffer = {};
  90854. texture._framebuffer = {};
  90855. texture.baseWidth = width;
  90856. texture.baseHeight = height;
  90857. texture.width = width;
  90858. texture.height = height;
  90859. texture.isReady = true;
  90860. texture.samples = 1;
  90861. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90862. texture.samplingMode = fullOptions.samplingMode;
  90863. texture.type = fullOptions.type;
  90864. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90865. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90866. return texture;
  90867. };
  90868. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90869. texture.samplingMode = samplingMode;
  90870. };
  90871. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90872. if (this._currentRenderTarget) {
  90873. this.unBindFramebuffer(this._currentRenderTarget);
  90874. }
  90875. this._currentRenderTarget = texture;
  90876. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90877. if (this._cachedViewport && !forceFullscreenViewport) {
  90878. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90879. }
  90880. };
  90881. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90882. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90883. this._currentRenderTarget = null;
  90884. if (onBeforeUnbind) {
  90885. if (texture._MSAAFramebuffer) {
  90886. this._currentFramebuffer = texture._framebuffer;
  90887. }
  90888. onBeforeUnbind();
  90889. }
  90890. this._currentFramebuffer = null;
  90891. };
  90892. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90893. var vbo = {
  90894. capacity: 1,
  90895. references: 1,
  90896. is32Bits: false
  90897. };
  90898. return vbo;
  90899. };
  90900. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90901. if (offset === void 0) { offset = 0; }
  90902. };
  90903. /**
  90904. * Updates a dynamic vertex buffer.
  90905. * @param vertexBuffer the vertex buffer to update
  90906. * @param data the data used to update the vertex buffer
  90907. * @param byteOffset the byte offset of the data (optional)
  90908. * @param byteLength the byte length of the data (optional)
  90909. */
  90910. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  90911. };
  90912. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90913. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90914. this._boundTexturesCache[this._activeChannel] = texture;
  90915. }
  90916. };
  90917. NullEngine.prototype._bindTexture = function (channel, texture) {
  90918. if (channel < 0) {
  90919. return;
  90920. }
  90921. this._bindTextureDirectly(0, texture);
  90922. };
  90923. NullEngine.prototype._releaseBuffer = function (buffer) {
  90924. buffer.references--;
  90925. if (buffer.references === 0) {
  90926. return true;
  90927. }
  90928. return false;
  90929. };
  90930. return NullEngine;
  90931. }(BABYLON.Engine));
  90932. BABYLON.NullEngine = NullEngine;
  90933. })(BABYLON || (BABYLON = {}));
  90934. //# sourceMappingURL=babylon.nullEngine.js.map
  90935. "use strict";
  90936. var BABYLON;
  90937. (function (BABYLON) {
  90938. /**
  90939. * This class can be used to get instrumentation data from a Babylon engine
  90940. */
  90941. var EngineInstrumentation = /** @class */ (function () {
  90942. function EngineInstrumentation(engine) {
  90943. this.engine = engine;
  90944. this._captureGPUFrameTime = false;
  90945. this._gpuFrameTime = new BABYLON.PerfCounter();
  90946. this._captureShaderCompilationTime = false;
  90947. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90948. // Observers
  90949. this._onBeginFrameObserver = null;
  90950. this._onEndFrameObserver = null;
  90951. this._onBeforeShaderCompilationObserver = null;
  90952. this._onAfterShaderCompilationObserver = null;
  90953. }
  90954. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90955. // Properties
  90956. /**
  90957. * Gets the perf counter used for GPU frame time
  90958. */
  90959. get: function () {
  90960. return this._gpuFrameTime;
  90961. },
  90962. enumerable: true,
  90963. configurable: true
  90964. });
  90965. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90966. /**
  90967. * Gets the GPU frame time capture status
  90968. */
  90969. get: function () {
  90970. return this._captureGPUFrameTime;
  90971. },
  90972. /**
  90973. * Enable or disable the GPU frame time capture
  90974. */
  90975. set: function (value) {
  90976. var _this = this;
  90977. if (value === this._captureGPUFrameTime) {
  90978. return;
  90979. }
  90980. this._captureGPUFrameTime = value;
  90981. if (value) {
  90982. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90983. if (!_this._gpuFrameTimeToken) {
  90984. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90985. }
  90986. });
  90987. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90988. if (!_this._gpuFrameTimeToken) {
  90989. return;
  90990. }
  90991. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90992. if (time > -1) {
  90993. _this._gpuFrameTimeToken = null;
  90994. _this._gpuFrameTime.fetchNewFrame();
  90995. _this._gpuFrameTime.addCount(time, true);
  90996. }
  90997. });
  90998. }
  90999. else {
  91000. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  91001. this._onBeginFrameObserver = null;
  91002. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  91003. this._onEndFrameObserver = null;
  91004. }
  91005. },
  91006. enumerable: true,
  91007. configurable: true
  91008. });
  91009. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  91010. /**
  91011. * Gets the perf counter used for shader compilation time
  91012. */
  91013. get: function () {
  91014. return this._shaderCompilationTime;
  91015. },
  91016. enumerable: true,
  91017. configurable: true
  91018. });
  91019. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  91020. /**
  91021. * Gets the shader compilation time capture status
  91022. */
  91023. get: function () {
  91024. return this._captureShaderCompilationTime;
  91025. },
  91026. /**
  91027. * Enable or disable the shader compilation time capture
  91028. */
  91029. set: function (value) {
  91030. var _this = this;
  91031. if (value === this._captureShaderCompilationTime) {
  91032. return;
  91033. }
  91034. this._captureShaderCompilationTime = value;
  91035. if (value) {
  91036. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  91037. _this._shaderCompilationTime.fetchNewFrame();
  91038. _this._shaderCompilationTime.beginMonitoring();
  91039. });
  91040. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  91041. _this._shaderCompilationTime.endMonitoring();
  91042. });
  91043. }
  91044. else {
  91045. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  91046. this._onBeforeShaderCompilationObserver = null;
  91047. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  91048. this._onAfterShaderCompilationObserver = null;
  91049. }
  91050. },
  91051. enumerable: true,
  91052. configurable: true
  91053. });
  91054. EngineInstrumentation.prototype.dispose = function () {
  91055. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  91056. this._onBeginFrameObserver = null;
  91057. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  91058. this._onEndFrameObserver = null;
  91059. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  91060. this._onBeforeShaderCompilationObserver = null;
  91061. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  91062. this._onAfterShaderCompilationObserver = null;
  91063. this.engine = null;
  91064. };
  91065. return EngineInstrumentation;
  91066. }());
  91067. BABYLON.EngineInstrumentation = EngineInstrumentation;
  91068. })(BABYLON || (BABYLON = {}));
  91069. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  91070. "use strict";
  91071. var BABYLON;
  91072. (function (BABYLON) {
  91073. /**
  91074. * This class can be used to get instrumentation data from a Babylon engine
  91075. */
  91076. var SceneInstrumentation = /** @class */ (function () {
  91077. function SceneInstrumentation(scene) {
  91078. var _this = this;
  91079. this.scene = scene;
  91080. this._captureActiveMeshesEvaluationTime = false;
  91081. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  91082. this._captureRenderTargetsRenderTime = false;
  91083. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  91084. this._captureFrameTime = false;
  91085. this._frameTime = new BABYLON.PerfCounter();
  91086. this._captureRenderTime = false;
  91087. this._renderTime = new BABYLON.PerfCounter();
  91088. this._captureInterFrameTime = false;
  91089. this._interFrameTime = new BABYLON.PerfCounter();
  91090. this._captureParticlesRenderTime = false;
  91091. this._particlesRenderTime = new BABYLON.PerfCounter();
  91092. this._captureSpritesRenderTime = false;
  91093. this._spritesRenderTime = new BABYLON.PerfCounter();
  91094. this._capturePhysicsTime = false;
  91095. this._physicsTime = new BABYLON.PerfCounter();
  91096. this._captureAnimationsTime = false;
  91097. this._animationsTime = new BABYLON.PerfCounter();
  91098. // Observers
  91099. this._onBeforeActiveMeshesEvaluationObserver = null;
  91100. this._onAfterActiveMeshesEvaluationObserver = null;
  91101. this._onBeforeRenderTargetsRenderObserver = null;
  91102. this._onAfterRenderTargetsRenderObserver = null;
  91103. this._onAfterRenderObserver = null;
  91104. this._onBeforeDrawPhaseObserver = null;
  91105. this._onAfterDrawPhaseObserver = null;
  91106. this._onBeforeAnimationsObserver = null;
  91107. this._onBeforeParticlesRenderingObserver = null;
  91108. this._onAfterParticlesRenderingObserver = null;
  91109. this._onBeforeSpritesRenderingObserver = null;
  91110. this._onAfterSpritesRenderingObserver = null;
  91111. this._onBeforePhysicsObserver = null;
  91112. this._onAfterPhysicsObserver = null;
  91113. this._onAfterAnimationsObserver = null;
  91114. // Before render
  91115. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  91116. if (_this._captureActiveMeshesEvaluationTime) {
  91117. _this._activeMeshesEvaluationTime.fetchNewFrame();
  91118. }
  91119. if (_this._captureRenderTargetsRenderTime) {
  91120. _this._renderTargetsRenderTime.fetchNewFrame();
  91121. }
  91122. if (_this._captureFrameTime) {
  91123. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  91124. _this._frameTime.beginMonitoring();
  91125. }
  91126. if (_this._captureInterFrameTime) {
  91127. _this._interFrameTime.endMonitoring();
  91128. }
  91129. if (_this._captureParticlesRenderTime) {
  91130. _this._particlesRenderTime.fetchNewFrame();
  91131. }
  91132. if (_this._captureSpritesRenderTime) {
  91133. _this._spritesRenderTime.fetchNewFrame();
  91134. }
  91135. if (_this._captureAnimationsTime) {
  91136. _this._animationsTime.beginMonitoring();
  91137. }
  91138. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  91139. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  91140. });
  91141. // After render
  91142. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  91143. if (_this._captureFrameTime) {
  91144. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  91145. _this._frameTime.endMonitoring();
  91146. }
  91147. if (_this._captureRenderTime) {
  91148. _this._renderTime.endMonitoring(false);
  91149. }
  91150. if (_this._captureInterFrameTime) {
  91151. _this._interFrameTime.beginMonitoring();
  91152. }
  91153. });
  91154. }
  91155. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  91156. // Properties
  91157. /**
  91158. * Gets the perf counter used for active meshes evaluation time
  91159. */
  91160. get: function () {
  91161. return this._activeMeshesEvaluationTime;
  91162. },
  91163. enumerable: true,
  91164. configurable: true
  91165. });
  91166. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  91167. /**
  91168. * Gets the active meshes evaluation time capture status
  91169. */
  91170. get: function () {
  91171. return this._captureActiveMeshesEvaluationTime;
  91172. },
  91173. /**
  91174. * Enable or disable the active meshes evaluation time capture
  91175. */
  91176. set: function (value) {
  91177. var _this = this;
  91178. if (value === this._captureActiveMeshesEvaluationTime) {
  91179. return;
  91180. }
  91181. this._captureActiveMeshesEvaluationTime = value;
  91182. if (value) {
  91183. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  91184. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  91185. _this._activeMeshesEvaluationTime.beginMonitoring();
  91186. });
  91187. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  91188. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  91189. _this._activeMeshesEvaluationTime.endMonitoring();
  91190. });
  91191. }
  91192. else {
  91193. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  91194. this._onBeforeActiveMeshesEvaluationObserver = null;
  91195. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  91196. this._onAfterActiveMeshesEvaluationObserver = null;
  91197. }
  91198. },
  91199. enumerable: true,
  91200. configurable: true
  91201. });
  91202. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  91203. /**
  91204. * Gets the perf counter used for render targets render time
  91205. */
  91206. get: function () {
  91207. return this._renderTargetsRenderTime;
  91208. },
  91209. enumerable: true,
  91210. configurable: true
  91211. });
  91212. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  91213. /**
  91214. * Gets the render targets render time capture status
  91215. */
  91216. get: function () {
  91217. return this._captureRenderTargetsRenderTime;
  91218. },
  91219. /**
  91220. * Enable or disable the render targets render time capture
  91221. */
  91222. set: function (value) {
  91223. var _this = this;
  91224. if (value === this._captureRenderTargetsRenderTime) {
  91225. return;
  91226. }
  91227. this._captureRenderTargetsRenderTime = value;
  91228. if (value) {
  91229. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  91230. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  91231. _this._renderTargetsRenderTime.beginMonitoring();
  91232. });
  91233. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  91234. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  91235. _this._renderTargetsRenderTime.endMonitoring(false);
  91236. });
  91237. }
  91238. else {
  91239. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  91240. this._onBeforeRenderTargetsRenderObserver = null;
  91241. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  91242. this._onAfterRenderTargetsRenderObserver = null;
  91243. }
  91244. },
  91245. enumerable: true,
  91246. configurable: true
  91247. });
  91248. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  91249. /**
  91250. * Gets the perf counter used for particles render time
  91251. */
  91252. get: function () {
  91253. return this._particlesRenderTime;
  91254. },
  91255. enumerable: true,
  91256. configurable: true
  91257. });
  91258. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  91259. /**
  91260. * Gets the particles render time capture status
  91261. */
  91262. get: function () {
  91263. return this._captureParticlesRenderTime;
  91264. },
  91265. /**
  91266. * Enable or disable the particles render time capture
  91267. */
  91268. set: function (value) {
  91269. var _this = this;
  91270. if (value === this._captureParticlesRenderTime) {
  91271. return;
  91272. }
  91273. this._captureParticlesRenderTime = value;
  91274. if (value) {
  91275. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  91276. BABYLON.Tools.StartPerformanceCounter("Particles");
  91277. _this._particlesRenderTime.beginMonitoring();
  91278. });
  91279. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  91280. BABYLON.Tools.EndPerformanceCounter("Particles");
  91281. _this._particlesRenderTime.endMonitoring(false);
  91282. });
  91283. }
  91284. else {
  91285. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  91286. this._onBeforeParticlesRenderingObserver = null;
  91287. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  91288. this._onAfterParticlesRenderingObserver = null;
  91289. }
  91290. },
  91291. enumerable: true,
  91292. configurable: true
  91293. });
  91294. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  91295. /**
  91296. * Gets the perf counter used for sprites render time
  91297. */
  91298. get: function () {
  91299. return this._spritesRenderTime;
  91300. },
  91301. enumerable: true,
  91302. configurable: true
  91303. });
  91304. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  91305. /**
  91306. * Gets the sprites render time capture status
  91307. */
  91308. get: function () {
  91309. return this._captureSpritesRenderTime;
  91310. },
  91311. /**
  91312. * Enable or disable the sprites render time capture
  91313. */
  91314. set: function (value) {
  91315. var _this = this;
  91316. if (value === this._captureSpritesRenderTime) {
  91317. return;
  91318. }
  91319. this._captureSpritesRenderTime = value;
  91320. if (value) {
  91321. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  91322. BABYLON.Tools.StartPerformanceCounter("Sprites");
  91323. _this._spritesRenderTime.beginMonitoring();
  91324. });
  91325. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  91326. BABYLON.Tools.EndPerformanceCounter("Sprites");
  91327. _this._spritesRenderTime.endMonitoring(false);
  91328. });
  91329. }
  91330. else {
  91331. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91332. this._onBeforeSpritesRenderingObserver = null;
  91333. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91334. this._onAfterSpritesRenderingObserver = null;
  91335. }
  91336. },
  91337. enumerable: true,
  91338. configurable: true
  91339. });
  91340. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  91341. /**
  91342. * Gets the perf counter used for physics time
  91343. */
  91344. get: function () {
  91345. return this._physicsTime;
  91346. },
  91347. enumerable: true,
  91348. configurable: true
  91349. });
  91350. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  91351. /**
  91352. * Gets the physics time capture status
  91353. */
  91354. get: function () {
  91355. return this._capturePhysicsTime;
  91356. },
  91357. /**
  91358. * Enable or disable the physics time capture
  91359. */
  91360. set: function (value) {
  91361. var _this = this;
  91362. if (value === this._capturePhysicsTime) {
  91363. return;
  91364. }
  91365. this._capturePhysicsTime = value;
  91366. if (value) {
  91367. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  91368. BABYLON.Tools.StartPerformanceCounter("Physics");
  91369. _this._physicsTime.beginMonitoring();
  91370. });
  91371. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  91372. BABYLON.Tools.EndPerformanceCounter("Physics");
  91373. _this._physicsTime.endMonitoring();
  91374. });
  91375. }
  91376. else {
  91377. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91378. this._onBeforePhysicsObserver = null;
  91379. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91380. this._onAfterPhysicsObserver = null;
  91381. }
  91382. },
  91383. enumerable: true,
  91384. configurable: true
  91385. });
  91386. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  91387. /**
  91388. * Gets the perf counter used for animations time
  91389. */
  91390. get: function () {
  91391. return this._animationsTime;
  91392. },
  91393. enumerable: true,
  91394. configurable: true
  91395. });
  91396. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  91397. /**
  91398. * Gets the animations time capture status
  91399. */
  91400. get: function () {
  91401. return this._captureAnimationsTime;
  91402. },
  91403. /**
  91404. * Enable or disable the animations time capture
  91405. */
  91406. set: function (value) {
  91407. var _this = this;
  91408. if (value === this._captureAnimationsTime) {
  91409. return;
  91410. }
  91411. this._captureAnimationsTime = value;
  91412. if (value) {
  91413. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  91414. _this._animationsTime.endMonitoring();
  91415. });
  91416. }
  91417. else {
  91418. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91419. this._onAfterAnimationsObserver = null;
  91420. }
  91421. },
  91422. enumerable: true,
  91423. configurable: true
  91424. });
  91425. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  91426. /**
  91427. * Gets the perf counter used for frame time capture
  91428. */
  91429. get: function () {
  91430. return this._frameTime;
  91431. },
  91432. enumerable: true,
  91433. configurable: true
  91434. });
  91435. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  91436. /**
  91437. * Gets the frame time capture status
  91438. */
  91439. get: function () {
  91440. return this._captureFrameTime;
  91441. },
  91442. /**
  91443. * Enable or disable the frame time capture
  91444. */
  91445. set: function (value) {
  91446. this._captureFrameTime = value;
  91447. },
  91448. enumerable: true,
  91449. configurable: true
  91450. });
  91451. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  91452. /**
  91453. * Gets the perf counter used for inter-frames time capture
  91454. */
  91455. get: function () {
  91456. return this._interFrameTime;
  91457. },
  91458. enumerable: true,
  91459. configurable: true
  91460. });
  91461. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  91462. /**
  91463. * Gets the inter-frames time capture status
  91464. */
  91465. get: function () {
  91466. return this._captureInterFrameTime;
  91467. },
  91468. /**
  91469. * Enable or disable the inter-frames time capture
  91470. */
  91471. set: function (value) {
  91472. this._captureInterFrameTime = value;
  91473. },
  91474. enumerable: true,
  91475. configurable: true
  91476. });
  91477. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  91478. /**
  91479. * Gets the perf counter used for render time capture
  91480. */
  91481. get: function () {
  91482. return this._renderTime;
  91483. },
  91484. enumerable: true,
  91485. configurable: true
  91486. });
  91487. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  91488. /**
  91489. * Gets the render time capture status
  91490. */
  91491. get: function () {
  91492. return this._captureRenderTime;
  91493. },
  91494. /**
  91495. * Enable or disable the render time capture
  91496. */
  91497. set: function (value) {
  91498. var _this = this;
  91499. if (value === this._captureRenderTime) {
  91500. return;
  91501. }
  91502. this._captureRenderTime = value;
  91503. if (value) {
  91504. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  91505. _this._renderTime.beginMonitoring();
  91506. BABYLON.Tools.StartPerformanceCounter("Main render");
  91507. });
  91508. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  91509. _this._renderTime.endMonitoring(false);
  91510. BABYLON.Tools.EndPerformanceCounter("Main render");
  91511. });
  91512. }
  91513. else {
  91514. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91515. this._onBeforeDrawPhaseObserver = null;
  91516. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91517. this._onAfterDrawPhaseObserver = null;
  91518. }
  91519. },
  91520. enumerable: true,
  91521. configurable: true
  91522. });
  91523. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  91524. /**
  91525. * Gets the perf counter used for draw calls
  91526. */
  91527. get: function () {
  91528. return this.scene.getEngine()._drawCalls;
  91529. },
  91530. enumerable: true,
  91531. configurable: true
  91532. });
  91533. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  91534. /**
  91535. * Gets the perf counter used for texture collisions
  91536. */
  91537. get: function () {
  91538. return this.scene.getEngine()._textureCollisions;
  91539. },
  91540. enumerable: true,
  91541. configurable: true
  91542. });
  91543. SceneInstrumentation.prototype.dispose = function () {
  91544. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91545. this._onAfterRenderObserver = null;
  91546. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  91547. this._onBeforeActiveMeshesEvaluationObserver = null;
  91548. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  91549. this._onAfterActiveMeshesEvaluationObserver = null;
  91550. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  91551. this._onBeforeRenderTargetsRenderObserver = null;
  91552. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  91553. this._onAfterRenderTargetsRenderObserver = null;
  91554. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  91555. this._onBeforeAnimationsObserver = null;
  91556. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  91557. this._onBeforeParticlesRenderingObserver = null;
  91558. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  91559. this._onAfterParticlesRenderingObserver = null;
  91560. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91561. this._onBeforeSpritesRenderingObserver = null;
  91562. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91563. this._onAfterSpritesRenderingObserver = null;
  91564. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91565. this._onBeforeDrawPhaseObserver = null;
  91566. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91567. this._onAfterDrawPhaseObserver = null;
  91568. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91569. this._onBeforePhysicsObserver = null;
  91570. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91571. this._onAfterPhysicsObserver = null;
  91572. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91573. this._onAfterAnimationsObserver = null;
  91574. this.scene = null;
  91575. };
  91576. return SceneInstrumentation;
  91577. }());
  91578. BABYLON.SceneInstrumentation = SceneInstrumentation;
  91579. })(BABYLON || (BABYLON = {}));
  91580. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  91581. "use strict";
  91582. var BABYLON;
  91583. (function (BABYLON) {
  91584. var _TimeToken = /** @class */ (function () {
  91585. function _TimeToken() {
  91586. this._timeElapsedQueryEnded = false;
  91587. }
  91588. return _TimeToken;
  91589. }());
  91590. BABYLON._TimeToken = _TimeToken;
  91591. })(BABYLON || (BABYLON = {}));
  91592. //# sourceMappingURL=babylon.timeToken.js.map
  91593. "use strict";
  91594. var BABYLON;
  91595. (function (BABYLON) {
  91596. /**
  91597. * Background material defines definition.
  91598. * @ignore Mainly internal Use
  91599. */
  91600. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  91601. __extends(BackgroundMaterialDefines, _super);
  91602. /**
  91603. * Constructor of the defines.
  91604. */
  91605. function BackgroundMaterialDefines() {
  91606. var _this = _super.call(this) || this;
  91607. /**
  91608. * True if the diffuse texture is in use.
  91609. */
  91610. _this.DIFFUSE = false;
  91611. /**
  91612. * The direct UV channel to use.
  91613. */
  91614. _this.DIFFUSEDIRECTUV = 0;
  91615. /**
  91616. * True if the diffuse texture is in gamma space.
  91617. */
  91618. _this.GAMMADIFFUSE = false;
  91619. /**
  91620. * True if the diffuse texture has opacity in the alpha channel.
  91621. */
  91622. _this.DIFFUSEHASALPHA = false;
  91623. /**
  91624. * True if you want the material to fade to transparent at grazing angle.
  91625. */
  91626. _this.OPACITYFRESNEL = false;
  91627. /**
  91628. * True if an extra blur needs to be added in the reflection.
  91629. */
  91630. _this.REFLECTIONBLUR = false;
  91631. /**
  91632. * True if you want the material to fade to reflection at grazing angle.
  91633. */
  91634. _this.REFLECTIONFRESNEL = false;
  91635. /**
  91636. * True if you want the material to falloff as far as you move away from the scene center.
  91637. */
  91638. _this.REFLECTIONFALLOFF = false;
  91639. /**
  91640. * False if the current Webgl implementation does not support the texture lod extension.
  91641. */
  91642. _this.TEXTURELODSUPPORT = false;
  91643. /**
  91644. * True to ensure the data are premultiplied.
  91645. */
  91646. _this.PREMULTIPLYALPHA = false;
  91647. /**
  91648. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  91649. */
  91650. _this.USERGBCOLOR = false;
  91651. /**
  91652. * True to add noise in order to reduce the banding effect.
  91653. */
  91654. _this.NOISE = false;
  91655. /**
  91656. * is the reflection texture in BGR color scheme?
  91657. * Mainly used to solve a bug in ios10 video tag
  91658. */
  91659. _this.REFLECTIONBGR = false;
  91660. _this.IMAGEPROCESSING = false;
  91661. _this.VIGNETTE = false;
  91662. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  91663. _this.VIGNETTEBLENDMODEOPAQUE = false;
  91664. _this.TONEMAPPING = false;
  91665. _this.CONTRAST = false;
  91666. _this.COLORCURVES = false;
  91667. _this.COLORGRADING = false;
  91668. _this.COLORGRADING3D = false;
  91669. _this.SAMPLER3DGREENDEPTH = false;
  91670. _this.SAMPLER3DBGRMAP = false;
  91671. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  91672. _this.EXPOSURE = false;
  91673. // Reflection.
  91674. _this.REFLECTION = false;
  91675. _this.REFLECTIONMAP_3D = false;
  91676. _this.REFLECTIONMAP_SPHERICAL = false;
  91677. _this.REFLECTIONMAP_PLANAR = false;
  91678. _this.REFLECTIONMAP_CUBIC = false;
  91679. _this.REFLECTIONMAP_PROJECTION = false;
  91680. _this.REFLECTIONMAP_SKYBOX = false;
  91681. _this.REFLECTIONMAP_EXPLICIT = false;
  91682. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91683. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91684. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91685. _this.INVERTCUBICMAP = false;
  91686. _this.REFLECTIONMAP_OPPOSITEZ = false;
  91687. _this.LODINREFLECTIONALPHA = false;
  91688. _this.GAMMAREFLECTION = false;
  91689. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  91690. // Default BJS.
  91691. _this.MAINUV1 = false;
  91692. _this.MAINUV2 = false;
  91693. _this.UV1 = false;
  91694. _this.UV2 = false;
  91695. _this.CLIPPLANE = false;
  91696. _this.POINTSIZE = false;
  91697. _this.FOG = false;
  91698. _this.NORMAL = false;
  91699. _this.NUM_BONE_INFLUENCERS = 0;
  91700. _this.BonesPerMesh = 0;
  91701. _this.INSTANCES = false;
  91702. _this.SHADOWFLOAT = false;
  91703. _this.rebuild();
  91704. return _this;
  91705. }
  91706. return BackgroundMaterialDefines;
  91707. }(BABYLON.MaterialDefines));
  91708. /**
  91709. * Background material used to create an efficient environement around your scene.
  91710. */
  91711. var BackgroundMaterial = /** @class */ (function (_super) {
  91712. __extends(BackgroundMaterial, _super);
  91713. /**
  91714. * Instantiates a Background Material in the given scene
  91715. * @param name The friendly name of the material
  91716. * @param scene The scene to add the material to
  91717. */
  91718. function BackgroundMaterial(name, scene) {
  91719. var _this = _super.call(this, name, scene) || this;
  91720. /**
  91721. * Key light Color (multiply against the R channel of the environement texture)
  91722. */
  91723. _this.primaryColor = BABYLON.Color3.White();
  91724. /**
  91725. * Key light Level (allowing HDR output of the background)
  91726. */
  91727. _this.primaryLevel = 1;
  91728. /**
  91729. * Secondary light Color (multiply against the G channel of the environement texture)
  91730. */
  91731. _this.secondaryColor = BABYLON.Color3.Gray();
  91732. /**
  91733. * Secondary light Level (allowing HDR output of the background)
  91734. */
  91735. _this.secondaryLevel = 1;
  91736. /**
  91737. * Tertiary light Color (multiply against the B channel of the environement texture)
  91738. */
  91739. _this.tertiaryColor = BABYLON.Color3.Black();
  91740. /**
  91741. * Tertiary light Level (allowing HDR output of the background)
  91742. */
  91743. _this.tertiaryLevel = 1;
  91744. /**
  91745. * Reflection Texture used in the material.
  91746. * Should be author in a specific way for the best result (refer to the documentation).
  91747. */
  91748. _this.reflectionTexture = null;
  91749. /**
  91750. * Reflection Texture level of blur.
  91751. *
  91752. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91753. * texture twice.
  91754. */
  91755. _this.reflectionBlur = 0;
  91756. /**
  91757. * Diffuse Texture used in the material.
  91758. * Should be author in a specific way for the best result (refer to the documentation).
  91759. */
  91760. _this.diffuseTexture = null;
  91761. _this._shadowLights = null;
  91762. /**
  91763. * Specify the list of lights casting shadow on the material.
  91764. * All scene shadow lights will be included if null.
  91765. */
  91766. _this.shadowLights = null;
  91767. /**
  91768. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91769. * soft lighting on the background.
  91770. */
  91771. _this.shadowBlurScale = 1;
  91772. /**
  91773. * Helps adjusting the shadow to a softer level if required.
  91774. * 0 means black shadows and 1 means no shadows.
  91775. */
  91776. _this.shadowLevel = 0;
  91777. /**
  91778. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91779. * It is usually zero but might be interesting to modify according to your setup.
  91780. */
  91781. _this.sceneCenter = BABYLON.Vector3.Zero();
  91782. /**
  91783. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91784. * This helps ensuring a nice transition when the camera goes under the ground.
  91785. */
  91786. _this.opacityFresnel = true;
  91787. /**
  91788. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91789. * This helps adding a mirror texture on the ground.
  91790. */
  91791. _this.reflectionFresnel = false;
  91792. /**
  91793. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91794. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91795. */
  91796. _this.reflectionFalloffDistance = 0.0;
  91797. /**
  91798. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91799. */
  91800. _this.reflectionAmount = 1.0;
  91801. /**
  91802. * This specifies the weight of the reflection at grazing angle.
  91803. */
  91804. _this.reflectionReflectance0 = 0.05;
  91805. /**
  91806. * This specifies the weight of the reflection at a perpendicular point of view.
  91807. */
  91808. _this.reflectionReflectance90 = 0.5;
  91809. /**
  91810. * Helps to directly use the maps channels instead of their level.
  91811. */
  91812. _this.useRGBColor = true;
  91813. /**
  91814. * This helps reducing the banding effect that could occur on the background.
  91815. */
  91816. _this.enableNoise = false;
  91817. _this._fovMultiplier = 1.0;
  91818. /**
  91819. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91820. */
  91821. _this.useEquirectangularFOV = false;
  91822. _this._maxSimultaneousLights = 4;
  91823. /**
  91824. * Number of Simultaneous lights allowed on the material.
  91825. */
  91826. _this.maxSimultaneousLights = 4;
  91827. /**
  91828. * Keep track of the image processing observer to allow dispose and replace.
  91829. */
  91830. _this._imageProcessingObserver = null;
  91831. /**
  91832. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91833. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91834. */
  91835. _this.switchToBGR = false;
  91836. // Temp values kept as cache in the material.
  91837. _this._renderTargets = new BABYLON.SmartArray(16);
  91838. _this._reflectionControls = BABYLON.Vector4.Zero();
  91839. // Setup the default processing configuration to the scene.
  91840. _this._attachImageProcessingConfiguration(null);
  91841. _this.getRenderTargetTextures = function () {
  91842. _this._renderTargets.reset();
  91843. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91844. _this._renderTargets.push(_this._diffuseTexture);
  91845. }
  91846. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91847. _this._renderTargets.push(_this._reflectionTexture);
  91848. }
  91849. return _this._renderTargets;
  91850. };
  91851. return _this;
  91852. }
  91853. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91854. /**
  91855. * Sets the reflection reflectance fresnel values according to the default standard
  91856. * empirically know to work well :-)
  91857. */
  91858. set: function (value) {
  91859. var reflectionWeight = value;
  91860. if (reflectionWeight < 0.5) {
  91861. reflectionWeight = reflectionWeight * 2.0;
  91862. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91863. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91864. }
  91865. else {
  91866. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91867. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91868. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91869. }
  91870. },
  91871. enumerable: true,
  91872. configurable: true
  91873. });
  91874. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91875. /**
  91876. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91877. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91878. * Recommended to be keep at 1.0 except for special cases.
  91879. */
  91880. get: function () {
  91881. return this._fovMultiplier;
  91882. },
  91883. set: function (value) {
  91884. if (isNaN(value)) {
  91885. value = 1.0;
  91886. }
  91887. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91888. },
  91889. enumerable: true,
  91890. configurable: true
  91891. });
  91892. /**
  91893. * Attaches a new image processing configuration to the PBR Material.
  91894. * @param configuration (if null the scene configuration will be use)
  91895. */
  91896. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91897. var _this = this;
  91898. if (configuration === this._imageProcessingConfiguration) {
  91899. return;
  91900. }
  91901. // Detaches observer.
  91902. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91903. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91904. }
  91905. // Pick the scene configuration if needed.
  91906. if (!configuration) {
  91907. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91908. }
  91909. else {
  91910. this._imageProcessingConfiguration = configuration;
  91911. }
  91912. // Attaches observer.
  91913. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91914. _this._markAllSubMeshesAsImageProcessingDirty();
  91915. });
  91916. };
  91917. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91918. /**
  91919. * Gets the image processing configuration used either in this material.
  91920. */
  91921. get: function () {
  91922. return this._imageProcessingConfiguration;
  91923. },
  91924. /**
  91925. * Sets the Default image processing configuration used either in the this material.
  91926. *
  91927. * If sets to null, the scene one is in use.
  91928. */
  91929. set: function (value) {
  91930. this._attachImageProcessingConfiguration(value);
  91931. // Ensure the effect will be rebuilt.
  91932. this._markAllSubMeshesAsTexturesDirty();
  91933. },
  91934. enumerable: true,
  91935. configurable: true
  91936. });
  91937. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91938. /**
  91939. * Gets wether the color curves effect is enabled.
  91940. */
  91941. get: function () {
  91942. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91943. },
  91944. /**
  91945. * Sets wether the color curves effect is enabled.
  91946. */
  91947. set: function (value) {
  91948. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91949. },
  91950. enumerable: true,
  91951. configurable: true
  91952. });
  91953. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91954. /**
  91955. * Gets wether the color grading effect is enabled.
  91956. */
  91957. get: function () {
  91958. return this.imageProcessingConfiguration.colorGradingEnabled;
  91959. },
  91960. /**
  91961. * Gets wether the color grading effect is enabled.
  91962. */
  91963. set: function (value) {
  91964. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91965. },
  91966. enumerable: true,
  91967. configurable: true
  91968. });
  91969. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91970. /**
  91971. * Gets wether tonemapping is enabled or not.
  91972. */
  91973. get: function () {
  91974. return this._imageProcessingConfiguration.toneMappingEnabled;
  91975. },
  91976. /**
  91977. * Sets wether tonemapping is enabled or not
  91978. */
  91979. set: function (value) {
  91980. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91981. },
  91982. enumerable: true,
  91983. configurable: true
  91984. });
  91985. ;
  91986. ;
  91987. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91988. /**
  91989. * The camera exposure used on this material.
  91990. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91991. * This corresponds to a photographic exposure.
  91992. */
  91993. get: function () {
  91994. return this._imageProcessingConfiguration.exposure;
  91995. },
  91996. /**
  91997. * The camera exposure used on this material.
  91998. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91999. * This corresponds to a photographic exposure.
  92000. */
  92001. set: function (value) {
  92002. this._imageProcessingConfiguration.exposure = value;
  92003. },
  92004. enumerable: true,
  92005. configurable: true
  92006. });
  92007. ;
  92008. ;
  92009. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  92010. /**
  92011. * Gets The camera contrast used on this material.
  92012. */
  92013. get: function () {
  92014. return this._imageProcessingConfiguration.contrast;
  92015. },
  92016. /**
  92017. * Sets The camera contrast used on this material.
  92018. */
  92019. set: function (value) {
  92020. this._imageProcessingConfiguration.contrast = value;
  92021. },
  92022. enumerable: true,
  92023. configurable: true
  92024. });
  92025. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  92026. /**
  92027. * Gets the Color Grading 2D Lookup Texture.
  92028. */
  92029. get: function () {
  92030. return this._imageProcessingConfiguration.colorGradingTexture;
  92031. },
  92032. /**
  92033. * Sets the Color Grading 2D Lookup Texture.
  92034. */
  92035. set: function (value) {
  92036. this.imageProcessingConfiguration.colorGradingTexture = value;
  92037. },
  92038. enumerable: true,
  92039. configurable: true
  92040. });
  92041. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  92042. /**
  92043. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  92044. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  92045. * 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;
  92046. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  92047. */
  92048. get: function () {
  92049. return this.imageProcessingConfiguration.colorCurves;
  92050. },
  92051. /**
  92052. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  92053. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  92054. * 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;
  92055. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  92056. */
  92057. set: function (value) {
  92058. this.imageProcessingConfiguration.colorCurves = value;
  92059. },
  92060. enumerable: true,
  92061. configurable: true
  92062. });
  92063. /**
  92064. * The entire material has been created in order to prevent overdraw.
  92065. * @returns false
  92066. */
  92067. BackgroundMaterial.prototype.needAlphaTesting = function () {
  92068. return true;
  92069. };
  92070. /**
  92071. * The entire material has been created in order to prevent overdraw.
  92072. * @returns true if blending is enable
  92073. */
  92074. BackgroundMaterial.prototype.needAlphaBlending = function () {
  92075. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  92076. };
  92077. /**
  92078. * Checks wether the material is ready to be rendered for a given mesh.
  92079. * @param mesh The mesh to render
  92080. * @param subMesh The submesh to check against
  92081. * @param useInstances Specify wether or not the material is used with instances
  92082. * @returns true if all the dependencies are ready (Textures, Effects...)
  92083. */
  92084. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  92085. var _this = this;
  92086. if (useInstances === void 0) { useInstances = false; }
  92087. if (subMesh.effect && this.isFrozen) {
  92088. if (this._wasPreviouslyReady) {
  92089. return true;
  92090. }
  92091. }
  92092. if (!subMesh._materialDefines) {
  92093. subMesh._materialDefines = new BackgroundMaterialDefines();
  92094. }
  92095. var scene = this.getScene();
  92096. var defines = subMesh._materialDefines;
  92097. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  92098. if (defines._renderId === scene.getRenderId()) {
  92099. return true;
  92100. }
  92101. }
  92102. var engine = scene.getEngine();
  92103. // Lights
  92104. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  92105. defines._needNormals = true;
  92106. // Textures
  92107. if (defines._areTexturesDirty) {
  92108. defines._needUVs = false;
  92109. if (scene.texturesEnabled) {
  92110. if (scene.getEngine().getCaps().textureLOD) {
  92111. defines.TEXTURELODSUPPORT = true;
  92112. }
  92113. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  92114. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  92115. return false;
  92116. }
  92117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  92118. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  92119. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  92120. defines.OPACITYFRESNEL = this._opacityFresnel;
  92121. }
  92122. else {
  92123. defines.DIFFUSE = false;
  92124. defines.DIFFUSEHASALPHA = false;
  92125. defines.GAMMADIFFUSE = false;
  92126. defines.OPACITYFRESNEL = false;
  92127. }
  92128. var reflectionTexture = this._reflectionTexture;
  92129. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  92130. if (!reflectionTexture.isReadyOrNotBlocking()) {
  92131. return false;
  92132. }
  92133. defines.REFLECTION = true;
  92134. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  92135. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  92136. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  92137. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  92138. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  92139. defines.REFLECTIONBGR = this.switchToBGR;
  92140. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  92141. defines.INVERTCUBICMAP = true;
  92142. }
  92143. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  92144. switch (reflectionTexture.coordinatesMode) {
  92145. case BABYLON.Texture.CUBIC_MODE:
  92146. case BABYLON.Texture.INVCUBIC_MODE:
  92147. defines.REFLECTIONMAP_CUBIC = true;
  92148. break;
  92149. case BABYLON.Texture.EXPLICIT_MODE:
  92150. defines.REFLECTIONMAP_EXPLICIT = true;
  92151. break;
  92152. case BABYLON.Texture.PLANAR_MODE:
  92153. defines.REFLECTIONMAP_PLANAR = true;
  92154. break;
  92155. case BABYLON.Texture.PROJECTION_MODE:
  92156. defines.REFLECTIONMAP_PROJECTION = true;
  92157. break;
  92158. case BABYLON.Texture.SKYBOX_MODE:
  92159. defines.REFLECTIONMAP_SKYBOX = true;
  92160. break;
  92161. case BABYLON.Texture.SPHERICAL_MODE:
  92162. defines.REFLECTIONMAP_SPHERICAL = true;
  92163. break;
  92164. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  92165. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  92166. break;
  92167. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  92168. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  92169. break;
  92170. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  92171. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  92172. break;
  92173. }
  92174. if (this.reflectionFresnel) {
  92175. defines.REFLECTIONFRESNEL = true;
  92176. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  92177. this._reflectionControls.x = this.reflectionAmount;
  92178. this._reflectionControls.y = this.reflectionReflectance0;
  92179. this._reflectionControls.z = this.reflectionReflectance90;
  92180. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  92181. }
  92182. else {
  92183. defines.REFLECTIONFRESNEL = false;
  92184. defines.REFLECTIONFALLOFF = false;
  92185. }
  92186. }
  92187. else {
  92188. defines.REFLECTION = false;
  92189. defines.REFLECTIONFALLOFF = false;
  92190. defines.REFLECTIONBLUR = false;
  92191. defines.REFLECTIONMAP_3D = false;
  92192. defines.REFLECTIONMAP_SPHERICAL = false;
  92193. defines.REFLECTIONMAP_PLANAR = false;
  92194. defines.REFLECTIONMAP_CUBIC = false;
  92195. defines.REFLECTIONMAP_PROJECTION = false;
  92196. defines.REFLECTIONMAP_SKYBOX = false;
  92197. defines.REFLECTIONMAP_EXPLICIT = false;
  92198. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  92199. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  92200. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  92201. defines.INVERTCUBICMAP = false;
  92202. defines.REFLECTIONMAP_OPPOSITEZ = false;
  92203. defines.LODINREFLECTIONALPHA = false;
  92204. defines.GAMMAREFLECTION = false;
  92205. }
  92206. }
  92207. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  92208. defines.USERGBCOLOR = this._useRGBColor;
  92209. defines.NOISE = this._enableNoise;
  92210. }
  92211. if (defines._areImageProcessingDirty) {
  92212. if (!this._imageProcessingConfiguration.isReady()) {
  92213. return false;
  92214. }
  92215. this._imageProcessingConfiguration.prepareDefines(defines);
  92216. }
  92217. // Misc.
  92218. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  92219. // Values that need to be evaluated on every frame
  92220. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  92221. // Attribs
  92222. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  92223. if (mesh) {
  92224. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  92225. mesh.createNormals(true);
  92226. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  92227. }
  92228. }
  92229. }
  92230. // Get correct effect
  92231. if (defines.isDirty) {
  92232. defines.markAsProcessed();
  92233. scene.resetCachedMaterial();
  92234. // Fallbacks
  92235. var fallbacks = new BABYLON.EffectFallbacks();
  92236. if (defines.FOG) {
  92237. fallbacks.addFallback(0, "FOG");
  92238. }
  92239. if (defines.POINTSIZE) {
  92240. fallbacks.addFallback(1, "POINTSIZE");
  92241. }
  92242. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  92243. if (defines.NUM_BONE_INFLUENCERS > 0) {
  92244. fallbacks.addCPUSkinningFallback(0, mesh);
  92245. }
  92246. //Attributes
  92247. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92248. if (defines.NORMAL) {
  92249. attribs.push(BABYLON.VertexBuffer.NormalKind);
  92250. }
  92251. if (defines.UV1) {
  92252. attribs.push(BABYLON.VertexBuffer.UVKind);
  92253. }
  92254. if (defines.UV2) {
  92255. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92256. }
  92257. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  92258. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  92259. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  92260. "vFogInfos", "vFogColor", "pointSize",
  92261. "vClipPlane", "mBones",
  92262. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  92263. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  92264. "shadowLevel", "alpha",
  92265. "vBackgroundCenter", "vReflectionControl",
  92266. "vDiffuseInfos", "diffuseMatrix",
  92267. ];
  92268. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  92269. var uniformBuffers = ["Material", "Scene"];
  92270. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  92271. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  92272. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  92273. uniformsNames: uniforms,
  92274. uniformBuffersNames: uniformBuffers,
  92275. samplers: samplers,
  92276. defines: defines,
  92277. maxSimultaneousLights: this._maxSimultaneousLights
  92278. });
  92279. var onCompiled = function (effect) {
  92280. if (_this.onCompiled) {
  92281. _this.onCompiled(effect);
  92282. }
  92283. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  92284. };
  92285. var join = defines.toString();
  92286. subMesh.setEffect(scene.getEngine().createEffect("background", {
  92287. attributes: attribs,
  92288. uniformsNames: uniforms,
  92289. uniformBuffersNames: uniformBuffers,
  92290. samplers: samplers,
  92291. defines: join,
  92292. fallbacks: fallbacks,
  92293. onCompiled: onCompiled,
  92294. onError: this.onError,
  92295. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  92296. }, engine), defines);
  92297. this.buildUniformLayout();
  92298. }
  92299. if (!subMesh.effect || !subMesh.effect.isReady()) {
  92300. return false;
  92301. }
  92302. defines._renderId = scene.getRenderId();
  92303. this._wasPreviouslyReady = true;
  92304. return true;
  92305. };
  92306. /**
  92307. * Build the uniform buffer used in the material.
  92308. */
  92309. BackgroundMaterial.prototype.buildUniformLayout = function () {
  92310. // Order is important !
  92311. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  92312. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  92313. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  92314. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  92315. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  92316. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  92317. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  92318. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  92319. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  92320. this._uniformBuffer.addUniform("pointSize", 1);
  92321. this._uniformBuffer.addUniform("shadowLevel", 1);
  92322. this._uniformBuffer.addUniform("alpha", 1);
  92323. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  92324. this._uniformBuffer.addUniform("vReflectionControl", 4);
  92325. this._uniformBuffer.create();
  92326. };
  92327. /**
  92328. * Unbind the material.
  92329. */
  92330. BackgroundMaterial.prototype.unbind = function () {
  92331. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  92332. this._uniformBuffer.setTexture("diffuseSampler", null);
  92333. }
  92334. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  92335. this._uniformBuffer.setTexture("reflectionSampler", null);
  92336. }
  92337. _super.prototype.unbind.call(this);
  92338. };
  92339. /**
  92340. * Bind only the world matrix to the material.
  92341. * @param world The world matrix to bind.
  92342. */
  92343. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  92344. this._activeEffect.setMatrix("world", world);
  92345. };
  92346. /**
  92347. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  92348. * @param world The world matrix to bind.
  92349. * @param subMesh The submesh to bind for.
  92350. */
  92351. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  92352. var scene = this.getScene();
  92353. var defines = subMesh._materialDefines;
  92354. if (!defines) {
  92355. return;
  92356. }
  92357. var effect = subMesh.effect;
  92358. if (!effect) {
  92359. return;
  92360. }
  92361. this._activeEffect = effect;
  92362. // Matrices
  92363. this.bindOnlyWorldMatrix(world);
  92364. // Bones
  92365. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  92366. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  92367. if (mustRebind) {
  92368. this._uniformBuffer.bindToEffect(effect, "Material");
  92369. this.bindViewProjection(effect);
  92370. var reflectionTexture = this._reflectionTexture;
  92371. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  92372. // Texture uniforms
  92373. if (scene.texturesEnabled) {
  92374. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  92375. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  92376. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  92377. }
  92378. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  92379. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  92380. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  92381. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  92382. }
  92383. }
  92384. if (this.shadowLevel > 0) {
  92385. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  92386. }
  92387. this._uniformBuffer.updateFloat("alpha", this.alpha);
  92388. // Point size
  92389. if (this.pointsCloud) {
  92390. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  92391. }
  92392. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  92393. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  92394. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  92395. }
  92396. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  92397. // Textures
  92398. if (scene.texturesEnabled) {
  92399. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  92400. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  92401. }
  92402. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  92403. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  92404. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  92405. }
  92406. else if (!defines.REFLECTIONBLUR) {
  92407. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  92408. }
  92409. else {
  92410. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  92411. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  92412. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  92413. }
  92414. if (defines.REFLECTIONFRESNEL) {
  92415. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  92416. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  92417. }
  92418. }
  92419. }
  92420. // Clip plane
  92421. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  92422. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  92423. }
  92424. if (mustRebind || !this.isFrozen) {
  92425. if (scene.lightsEnabled) {
  92426. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  92427. }
  92428. // View
  92429. this.bindView(effect);
  92430. // Fog
  92431. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  92432. // image processing
  92433. this._imageProcessingConfiguration.bind(this._activeEffect);
  92434. }
  92435. this._uniformBuffer.update();
  92436. this._afterBind(mesh);
  92437. };
  92438. /**
  92439. * Dispose the material.
  92440. * @param forceDisposeEffect Force disposal of the associated effect.
  92441. * @param forceDisposeTextures Force disposal of the associated textures.
  92442. */
  92443. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  92444. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  92445. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  92446. if (forceDisposeTextures) {
  92447. if (this.diffuseTexture) {
  92448. this.diffuseTexture.dispose();
  92449. }
  92450. if (this.reflectionTexture) {
  92451. this.reflectionTexture.dispose();
  92452. }
  92453. }
  92454. this._renderTargets.dispose();
  92455. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  92456. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  92457. }
  92458. _super.prototype.dispose.call(this, forceDisposeEffect);
  92459. };
  92460. /**
  92461. * Clones the material.
  92462. * @param name The cloned name.
  92463. * @returns The cloned material.
  92464. */
  92465. BackgroundMaterial.prototype.clone = function (name) {
  92466. var _this = this;
  92467. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  92468. };
  92469. /**
  92470. * Serializes the current material to its JSON representation.
  92471. * @returns The JSON representation.
  92472. */
  92473. BackgroundMaterial.prototype.serialize = function () {
  92474. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92475. serializationObject.customType = "BABYLON.BackgroundMaterial";
  92476. return serializationObject;
  92477. };
  92478. /**
  92479. * Gets the class name of the material
  92480. * @returns "BackgroundMaterial"
  92481. */
  92482. BackgroundMaterial.prototype.getClassName = function () {
  92483. return "BackgroundMaterial";
  92484. };
  92485. /**
  92486. * Parse a JSON input to create back a background material.
  92487. * @param source The JSON data to parse
  92488. * @param scene The scene to create the parsed material in
  92489. * @param rootUrl The root url of the assets the material depends upon
  92490. * @returns the instantiated BackgroundMaterial.
  92491. */
  92492. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  92493. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  92494. };
  92495. /**
  92496. * Standard reflectance value at parallel view angle.
  92497. */
  92498. BackgroundMaterial.StandardReflectance0 = 0.05;
  92499. /**
  92500. * Standard reflectance value at grazing angle.
  92501. */
  92502. BackgroundMaterial.StandardReflectance90 = 0.5;
  92503. __decorate([
  92504. BABYLON.serializeAsColor3()
  92505. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  92506. __decorate([
  92507. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92508. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  92509. __decorate([
  92510. BABYLON.serialize()
  92511. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  92512. __decorate([
  92513. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92514. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  92515. __decorate([
  92516. BABYLON.serializeAsColor3()
  92517. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  92518. __decorate([
  92519. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92520. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  92521. __decorate([
  92522. BABYLON.serialize()
  92523. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  92524. __decorate([
  92525. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92526. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  92527. __decorate([
  92528. BABYLON.serializeAsColor3()
  92529. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  92530. __decorate([
  92531. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92532. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  92533. __decorate([
  92534. BABYLON.serialize()
  92535. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  92536. __decorate([
  92537. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92538. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  92539. __decorate([
  92540. BABYLON.serializeAsTexture()
  92541. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  92542. __decorate([
  92543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92544. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  92545. __decorate([
  92546. BABYLON.serialize()
  92547. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  92548. __decorate([
  92549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92550. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  92551. __decorate([
  92552. BABYLON.serializeAsTexture()
  92553. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  92554. __decorate([
  92555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92556. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  92557. __decorate([
  92558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92559. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  92560. __decorate([
  92561. BABYLON.serialize()
  92562. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  92563. __decorate([
  92564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92565. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  92566. __decorate([
  92567. BABYLON.serialize()
  92568. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  92569. __decorate([
  92570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92571. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  92572. __decorate([
  92573. BABYLON.serializeAsVector3()
  92574. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  92575. __decorate([
  92576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92577. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  92578. __decorate([
  92579. BABYLON.serialize()
  92580. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  92581. __decorate([
  92582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92583. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  92584. __decorate([
  92585. BABYLON.serialize()
  92586. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  92587. __decorate([
  92588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92589. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  92590. __decorate([
  92591. BABYLON.serialize()
  92592. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  92593. __decorate([
  92594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92595. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  92596. __decorate([
  92597. BABYLON.serialize()
  92598. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  92599. __decorate([
  92600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92601. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  92602. __decorate([
  92603. BABYLON.serialize()
  92604. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  92605. __decorate([
  92606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92607. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  92608. __decorate([
  92609. BABYLON.serialize()
  92610. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  92611. __decorate([
  92612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92613. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  92614. __decorate([
  92615. BABYLON.serialize()
  92616. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  92617. __decorate([
  92618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92619. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  92620. __decorate([
  92621. BABYLON.serialize()
  92622. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  92623. __decorate([
  92624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92625. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  92626. __decorate([
  92627. BABYLON.serialize()
  92628. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  92629. __decorate([
  92630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92631. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  92632. __decorate([
  92633. BABYLON.serializeAsImageProcessingConfiguration()
  92634. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  92635. return BackgroundMaterial;
  92636. }(BABYLON.PushMaterial));
  92637. BABYLON.BackgroundMaterial = BackgroundMaterial;
  92638. })(BABYLON || (BABYLON = {}));
  92639. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  92640. "use strict";
  92641. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92642. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92643. s = arguments[i];
  92644. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92645. t[p] = s[p];
  92646. }
  92647. return t;
  92648. };
  92649. var BABYLON;
  92650. (function (BABYLON) {
  92651. /**
  92652. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  92653. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  92654. * It also helps with the default setup of your imageProcessing configuration.
  92655. */
  92656. var EnvironmentHelper = /** @class */ (function () {
  92657. /**
  92658. * constructor
  92659. * @param options
  92660. * @param scene The scene to add the material to
  92661. */
  92662. function EnvironmentHelper(options, scene) {
  92663. var _this = this;
  92664. this._errorHandler = function (message, exception) {
  92665. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  92666. };
  92667. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  92668. this._scene = scene;
  92669. this.onErrorObservable = new BABYLON.Observable();
  92670. this._setupBackground();
  92671. this._setupImageProcessing();
  92672. }
  92673. /**
  92674. * Creates the default options for the helper.
  92675. */
  92676. EnvironmentHelper._getDefaultOptions = function () {
  92677. return {
  92678. createGround: true,
  92679. groundSize: 15,
  92680. groundTexture: this._groundTextureCDNUrl,
  92681. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92682. groundOpacity: 0.9,
  92683. enableGroundShadow: true,
  92684. groundShadowLevel: 0.5,
  92685. enableGroundMirror: false,
  92686. groundMirrorSizeRatio: 0.3,
  92687. groundMirrorBlurKernel: 64,
  92688. groundMirrorAmount: 1,
  92689. groundMirrorFresnelWeight: 1,
  92690. groundMirrorFallOffDistance: 0,
  92691. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  92692. groundYBias: 0.00001,
  92693. createSkybox: true,
  92694. skyboxSize: 20,
  92695. skyboxTexture: this._skyboxTextureCDNUrl,
  92696. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92697. backgroundYRotation: 0,
  92698. sizeAuto: true,
  92699. rootPosition: BABYLON.Vector3.Zero(),
  92700. setupImageProcessing: true,
  92701. environmentTexture: this._environmentTextureCDNUrl,
  92702. cameraExposure: 0.8,
  92703. cameraContrast: 1.2,
  92704. toneMappingEnabled: true,
  92705. };
  92706. };
  92707. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  92708. /**
  92709. * Gets the root mesh created by the helper.
  92710. */
  92711. get: function () {
  92712. return this._rootMesh;
  92713. },
  92714. enumerable: true,
  92715. configurable: true
  92716. });
  92717. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  92718. /**
  92719. * Gets the skybox created by the helper.
  92720. */
  92721. get: function () {
  92722. return this._skybox;
  92723. },
  92724. enumerable: true,
  92725. configurable: true
  92726. });
  92727. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  92728. /**
  92729. * Gets the skybox texture created by the helper.
  92730. */
  92731. get: function () {
  92732. return this._skyboxTexture;
  92733. },
  92734. enumerable: true,
  92735. configurable: true
  92736. });
  92737. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92738. /**
  92739. * Gets the skybox material created by the helper.
  92740. */
  92741. get: function () {
  92742. return this._skyboxMaterial;
  92743. },
  92744. enumerable: true,
  92745. configurable: true
  92746. });
  92747. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92748. /**
  92749. * Gets the ground mesh created by the helper.
  92750. */
  92751. get: function () {
  92752. return this._ground;
  92753. },
  92754. enumerable: true,
  92755. configurable: true
  92756. });
  92757. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92758. /**
  92759. * Gets the ground texture created by the helper.
  92760. */
  92761. get: function () {
  92762. return this._groundTexture;
  92763. },
  92764. enumerable: true,
  92765. configurable: true
  92766. });
  92767. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92768. /**
  92769. * Gets the ground mirror created by the helper.
  92770. */
  92771. get: function () {
  92772. return this._groundMirror;
  92773. },
  92774. enumerable: true,
  92775. configurable: true
  92776. });
  92777. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92778. /**
  92779. * Gets the ground mirror render list to helps pushing the meshes
  92780. * you wish in the ground reflection.
  92781. */
  92782. get: function () {
  92783. if (this._groundMirror) {
  92784. return this._groundMirror.renderList;
  92785. }
  92786. return null;
  92787. },
  92788. enumerable: true,
  92789. configurable: true
  92790. });
  92791. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92792. /**
  92793. * Gets the ground material created by the helper.
  92794. */
  92795. get: function () {
  92796. return this._groundMaterial;
  92797. },
  92798. enumerable: true,
  92799. configurable: true
  92800. });
  92801. /**
  92802. * Updates the background according to the new options
  92803. * @param options
  92804. */
  92805. EnvironmentHelper.prototype.updateOptions = function (options) {
  92806. var newOptions = __assign({}, this._options, options);
  92807. if (this._ground && !newOptions.createGround) {
  92808. this._ground.dispose();
  92809. this._ground = null;
  92810. }
  92811. if (this._groundMaterial && !newOptions.createGround) {
  92812. this._groundMaterial.dispose();
  92813. this._groundMaterial = null;
  92814. }
  92815. if (this._groundTexture) {
  92816. if (this._options.groundTexture != newOptions.groundTexture) {
  92817. this._groundTexture.dispose();
  92818. this._groundTexture = null;
  92819. }
  92820. }
  92821. if (this._skybox && !newOptions.createSkybox) {
  92822. this._skybox.dispose();
  92823. this._skybox = null;
  92824. }
  92825. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92826. this._skyboxMaterial.dispose();
  92827. this._skyboxMaterial = null;
  92828. }
  92829. if (this._skyboxTexture) {
  92830. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92831. this._skyboxTexture.dispose();
  92832. this._skyboxTexture = null;
  92833. }
  92834. }
  92835. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92836. this._groundMirror.dispose();
  92837. this._groundMirror = null;
  92838. }
  92839. if (this._scene.environmentTexture) {
  92840. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92841. this._scene.environmentTexture.dispose();
  92842. }
  92843. }
  92844. this._options = newOptions;
  92845. this._setupBackground();
  92846. this._setupImageProcessing();
  92847. };
  92848. /**
  92849. * Sets the primary color of all the available elements.
  92850. * @param color
  92851. */
  92852. EnvironmentHelper.prototype.setMainColor = function (color) {
  92853. if (this.groundMaterial) {
  92854. this.groundMaterial.primaryColor = color;
  92855. }
  92856. if (this.skyboxMaterial) {
  92857. this.skyboxMaterial.primaryColor = color;
  92858. }
  92859. if (this.groundMirror) {
  92860. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92861. }
  92862. };
  92863. /**
  92864. * Setup the image processing according to the specified options.
  92865. */
  92866. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92867. if (this._options.setupImageProcessing) {
  92868. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92869. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92870. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92871. this._setupEnvironmentTexture();
  92872. }
  92873. };
  92874. /**
  92875. * Setup the environment texture according to the specified options.
  92876. */
  92877. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92878. if (this._scene.environmentTexture) {
  92879. return;
  92880. }
  92881. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92882. this._scene.environmentTexture = this._options.environmentTexture;
  92883. return;
  92884. }
  92885. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92886. this._scene.environmentTexture = environmentTexture;
  92887. };
  92888. /**
  92889. * Setup the background according to the specified options.
  92890. */
  92891. EnvironmentHelper.prototype._setupBackground = function () {
  92892. if (!this._rootMesh) {
  92893. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92894. }
  92895. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92896. var sceneSize = this._getSceneSize();
  92897. if (this._options.createGround) {
  92898. this._setupGround(sceneSize);
  92899. this._setupGroundMaterial();
  92900. this._setupGroundDiffuseTexture();
  92901. if (this._options.enableGroundMirror) {
  92902. this._setupGroundMirrorTexture(sceneSize);
  92903. }
  92904. this._setupMirrorInGroundMaterial();
  92905. }
  92906. if (this._options.createSkybox) {
  92907. this._setupSkybox(sceneSize);
  92908. this._setupSkyboxMaterial();
  92909. this._setupSkyboxReflectionTexture();
  92910. }
  92911. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92912. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92913. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92914. };
  92915. /**
  92916. * Get the scene sizes according to the setup.
  92917. */
  92918. EnvironmentHelper.prototype._getSceneSize = function () {
  92919. var _this = this;
  92920. var groundSize = this._options.groundSize;
  92921. var skyboxSize = this._options.skyboxSize;
  92922. var rootPosition = this._options.rootPosition;
  92923. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92924. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92925. }
  92926. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92927. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92928. });
  92929. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92930. if (this._options.sizeAuto) {
  92931. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92932. this._scene.activeCamera.upperRadiusLimit) {
  92933. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92934. skyboxSize = groundSize;
  92935. }
  92936. var sceneDiagonalLenght = sceneDiagonal.length();
  92937. if (sceneDiagonalLenght > groundSize) {
  92938. groundSize = sceneDiagonalLenght * 2;
  92939. skyboxSize = groundSize;
  92940. }
  92941. // 10 % bigger.
  92942. groundSize *= 1.1;
  92943. skyboxSize *= 1.5;
  92944. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92945. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92946. }
  92947. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92948. };
  92949. /**
  92950. * Setup the ground according to the specified options.
  92951. */
  92952. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92953. var _this = this;
  92954. if (!this._ground) {
  92955. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92956. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92957. this._ground.parent = this._rootMesh;
  92958. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92959. }
  92960. this._ground.receiveShadows = this._options.enableGroundShadow;
  92961. };
  92962. /**
  92963. * Setup the ground material according to the specified options.
  92964. */
  92965. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92966. if (!this._groundMaterial) {
  92967. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92968. }
  92969. this._groundMaterial.alpha = this._options.groundOpacity;
  92970. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92971. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92972. this._groundMaterial.primaryLevel = 1;
  92973. this._groundMaterial.primaryColor = this._options.groundColor;
  92974. this._groundMaterial.secondaryLevel = 0;
  92975. this._groundMaterial.tertiaryLevel = 0;
  92976. this._groundMaterial.useRGBColor = false;
  92977. this._groundMaterial.enableNoise = true;
  92978. if (this._ground) {
  92979. this._ground.material = this._groundMaterial;
  92980. }
  92981. };
  92982. /**
  92983. * Setup the ground diffuse texture according to the specified options.
  92984. */
  92985. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92986. if (!this._groundMaterial) {
  92987. return;
  92988. }
  92989. if (this._groundTexture) {
  92990. return;
  92991. }
  92992. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92993. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92994. return;
  92995. }
  92996. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92997. diffuseTexture.gammaSpace = false;
  92998. diffuseTexture.hasAlpha = true;
  92999. this._groundMaterial.diffuseTexture = diffuseTexture;
  93000. };
  93001. /**
  93002. * Setup the ground mirror texture according to the specified options.
  93003. */
  93004. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  93005. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93006. if (!this._groundMirror) {
  93007. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  93008. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  93009. this._groundMirror.anisotropicFilteringLevel = 1;
  93010. this._groundMirror.wrapU = wrapping;
  93011. this._groundMirror.wrapV = wrapping;
  93012. this._groundMirror.gammaSpace = false;
  93013. if (this._groundMirror.renderList) {
  93014. for (var i = 0; i < this._scene.meshes.length; i++) {
  93015. var mesh = this._scene.meshes[i];
  93016. if (mesh !== this._ground &&
  93017. mesh !== this._skybox &&
  93018. mesh !== this._rootMesh) {
  93019. this._groundMirror.renderList.push(mesh);
  93020. }
  93021. }
  93022. }
  93023. }
  93024. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  93025. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  93026. };
  93027. /**
  93028. * Setup the ground to receive the mirror texture.
  93029. */
  93030. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  93031. if (this._groundMaterial) {
  93032. this._groundMaterial.reflectionTexture = this._groundMirror;
  93033. this._groundMaterial.reflectionFresnel = true;
  93034. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  93035. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  93036. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  93037. }
  93038. };
  93039. /**
  93040. * Setup the skybox according to the specified options.
  93041. */
  93042. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  93043. var _this = this;
  93044. if (!this._skybox) {
  93045. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  93046. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  93047. }
  93048. this._skybox.parent = this._rootMesh;
  93049. };
  93050. /**
  93051. * Setup the skybox material according to the specified options.
  93052. */
  93053. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  93054. if (!this._skybox) {
  93055. return;
  93056. }
  93057. if (!this._skyboxMaterial) {
  93058. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  93059. }
  93060. this._skyboxMaterial.useRGBColor = false;
  93061. this._skyboxMaterial.primaryLevel = 1;
  93062. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  93063. this._skyboxMaterial.secondaryLevel = 0;
  93064. this._skyboxMaterial.tertiaryLevel = 0;
  93065. this._skyboxMaterial.enableNoise = true;
  93066. this._skybox.material = this._skyboxMaterial;
  93067. };
  93068. /**
  93069. * Setup the skybox reflection texture according to the specified options.
  93070. */
  93071. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  93072. if (!this._skyboxMaterial) {
  93073. return;
  93074. }
  93075. if (this._skyboxTexture) {
  93076. return;
  93077. }
  93078. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  93079. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  93080. return;
  93081. }
  93082. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  93083. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  93084. this._skyboxTexture.gammaSpace = false;
  93085. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  93086. };
  93087. /**
  93088. * Dispose all the elements created by the Helper.
  93089. */
  93090. EnvironmentHelper.prototype.dispose = function () {
  93091. if (this._groundMaterial) {
  93092. this._groundMaterial.dispose(true, true);
  93093. }
  93094. if (this._skyboxMaterial) {
  93095. this._skyboxMaterial.dispose(true, true);
  93096. }
  93097. this._rootMesh.dispose(false);
  93098. };
  93099. /**
  93100. * Default ground texture URL.
  93101. */
  93102. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  93103. /**
  93104. * Default skybox texture URL.
  93105. */
  93106. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  93107. /**
  93108. * Default environment texture URL.
  93109. */
  93110. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  93111. return EnvironmentHelper;
  93112. }());
  93113. BABYLON.EnvironmentHelper = EnvironmentHelper;
  93114. })(BABYLON || (BABYLON = {}));
  93115. //# sourceMappingURL=babylon.environmentHelper.js.map
  93116. "use strict";
  93117. var BABYLON;
  93118. (function (BABYLON) {
  93119. /**
  93120. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  93121. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  93122. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  93123. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  93124. */
  93125. var VideoDome = /** @class */ (function (_super) {
  93126. __extends(VideoDome, _super);
  93127. /**
  93128. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  93129. * @param name Element's name, child elements will append suffixes for their own names.
  93130. * @param urlsOrVideo
  93131. * @param options An object containing optional or exposed sub element properties:
  93132. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  93133. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  93134. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  93135. * @param options **loop=true** Automatically loop video on end.
  93136. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  93137. */
  93138. function VideoDome(name, urlsOrVideo, options, scene) {
  93139. var _this = _super.call(this, name, scene) || this;
  93140. // set defaults and manage values
  93141. name = name || "videoDome";
  93142. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  93143. options.clickToPlay = Boolean(options.clickToPlay);
  93144. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  93145. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  93146. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  93147. // create
  93148. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  93149. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  93150. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  93151. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  93152. flat: false,
  93153. radius: options.size,
  93154. subdivisions: options.resolution,
  93155. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  93156. }, scene);
  93157. // configure material
  93158. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  93159. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  93160. material.reflectionTexture = _this._videoTexture;
  93161. material.useEquirectangularFOV = true;
  93162. material.fovMultiplier = 1.0;
  93163. // configure mesh
  93164. _this._mesh.material = material;
  93165. _this._mesh.parent = _this;
  93166. // optional configuration
  93167. if (options.clickToPlay) {
  93168. scene.onPointerUp = function () {
  93169. _this._videoTexture.video.play();
  93170. };
  93171. }
  93172. return _this;
  93173. }
  93174. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  93175. /**
  93176. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  93177. * Also see the options.resolution property.
  93178. */
  93179. get: function () {
  93180. return this._material.fovMultiplier;
  93181. },
  93182. set: function (value) {
  93183. this._material.fovMultiplier = value;
  93184. },
  93185. enumerable: true,
  93186. configurable: true
  93187. });
  93188. /**
  93189. * Releases resources associated with this node.
  93190. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  93191. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  93192. */
  93193. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  93194. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  93195. this._videoTexture.dispose();
  93196. this._mesh.dispose();
  93197. this._material.dispose();
  93198. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  93199. };
  93200. return VideoDome;
  93201. }(BABYLON.Node));
  93202. BABYLON.VideoDome = VideoDome;
  93203. })(BABYLON || (BABYLON = {}));
  93204. //# sourceMappingURL=babylon.videoDome.js.map
  93205. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\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;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=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\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\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#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\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\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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\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 vec3 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.z*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","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}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\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}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  93206. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(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 computeShadowWithPoissonSampling(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#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(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#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,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#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","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};","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","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  93207. globalObject["BABYLON"] = BABYLON;
  93208. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;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 Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var VideoDome = BABYLON.VideoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  93209. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };